1 use crate::def::{CtorKind, DefKind, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::{HirId, ItemLocalId};
4 use crate::intravisit::FnKind;
5 use crate::LangItem;
6
7 use rustc_ast::util::parser::ExprPrecedence;
8 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
9 use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, TraitObjectSyntax, UintTy};
10 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
11 pub use rustc_ast::{CaptureBy, Movability, Mutability};
12 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
13 use rustc_data_structures::fingerprint::Fingerprint;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::sorted_map::SortedMap;
16 use rustc_index::vec::IndexVec;
17 use rustc_macros::HashStable_Generic;
18 use rustc_span::source_map::Spanned;
19 use rustc_span::symbol::{kw, sym, Ident, Symbol};
20 use rustc_span::{def_id::LocalDefId, BytePos};
21 use rustc_span::{MultiSpan, Span, DUMMY_SP};
22 use rustc_target::asm::InlineAsmRegOrRegClass;
23 use rustc_target::spec::abi::Abi;
24
25 use smallvec::SmallVec;
26 use std::fmt;
27
28 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
29 pub struct Lifetime {
30 pub hir_id: HirId,
31 pub span: Span,
32
33 /// Either "`'a`", referring to a named lifetime definition,
34 /// or "``" (i.e., `kw::Empty`), for elision placeholders.
35 ///
36 /// HIR lowering inserts these placeholders in type paths that
37 /// refer to type definitions needing lifetime parameters,
38 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
39 pub name: LifetimeName,
40 }
41
42 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
43 #[derive(HashStable_Generic)]
44 pub enum ParamName {
45 /// Some user-given name like `T` or `'x`.
46 Plain(Ident),
47
48 /// Synthetic name generated when user elided a lifetime in an impl header.
49 ///
50 /// E.g., the lifetimes in cases like these:
51 ///
52 /// impl Foo for &u32
53 /// impl Foo<'_> for u32
54 ///
55 /// in that case, we rewrite to
56 ///
57 /// impl<'f> Foo for &'f u32
58 /// impl<'f> Foo<'f> for u32
59 ///
60 /// where `'f` is something like `Fresh(0)`. The indices are
61 /// unique per impl, but not necessarily continuous.
62 Fresh(usize),
63
64 /// Indicates an illegal name was given and an error has been
65 /// reported (so we should squelch other derived errors). Occurs
66 /// when, e.g., `'_` is used in the wrong place.
67 Error,
68 }
69
70 impl ParamName {
ident(&self) -> Ident71 pub fn ident(&self) -> Ident {
72 match *self {
73 ParamName::Plain(ident) => ident,
74 ParamName::Fresh(_) | ParamName::Error => {
75 Ident::with_dummy_span(kw::UnderscoreLifetime)
76 }
77 }
78 }
79
normalize_to_macros_2_0(&self) -> ParamName80 pub fn normalize_to_macros_2_0(&self) -> ParamName {
81 match *self {
82 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
83 param_name => param_name,
84 }
85 }
86 }
87
88 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
89 #[derive(HashStable_Generic)]
90 pub enum LifetimeName {
91 /// User-given names or fresh (synthetic) names.
92 Param(ParamName),
93
94 /// User wrote nothing (e.g., the lifetime in `&u32`).
95 Implicit,
96
97 /// Implicit lifetime in a context like `dyn Foo`. This is
98 /// distinguished from implicit lifetimes elsewhere because the
99 /// lifetime that they default to must appear elsewhere within the
100 /// enclosing type. This means that, in an `impl Trait` context, we
101 /// don't have to create a parameter for them. That is, `impl
102 /// Trait<Item = &u32>` expands to an opaque type like `type
103 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
104 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
105 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
106 /// that surrounding code knows not to create a lifetime
107 /// parameter.
108 ImplicitObjectLifetimeDefault,
109
110 /// Indicates an error during lowering (usually `'_` in wrong place)
111 /// that was already reported.
112 Error,
113
114 /// User wrote specifies `'_`.
115 Underscore,
116
117 /// User wrote `'static`.
118 Static,
119 }
120
121 impl LifetimeName {
ident(&self) -> Ident122 pub fn ident(&self) -> Ident {
123 match *self {
124 LifetimeName::ImplicitObjectLifetimeDefault
125 | LifetimeName::Implicit
126 | LifetimeName::Error => Ident::empty(),
127 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
128 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
129 LifetimeName::Param(param_name) => param_name.ident(),
130 }
131 }
132
is_elided(&self) -> bool133 pub fn is_elided(&self) -> bool {
134 match self {
135 LifetimeName::ImplicitObjectLifetimeDefault
136 | LifetimeName::Implicit
137 | LifetimeName::Underscore => true,
138
139 // It might seem surprising that `Fresh(_)` counts as
140 // *not* elided -- but this is because, as far as the code
141 // in the compiler is concerned -- `Fresh(_)` variants act
142 // equivalently to "some fresh name". They correspond to
143 // early-bound regions on an impl, in other words.
144 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
145 }
146 }
147
is_static(&self) -> bool148 fn is_static(&self) -> bool {
149 self == &LifetimeName::Static
150 }
151
normalize_to_macros_2_0(&self) -> LifetimeName152 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
153 match *self {
154 LifetimeName::Param(param_name) => {
155 LifetimeName::Param(param_name.normalize_to_macros_2_0())
156 }
157 lifetime_name => lifetime_name,
158 }
159 }
160 }
161
162 impl fmt::Display for Lifetime {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 self.name.ident().fmt(f)
165 }
166 }
167
168 impl fmt::Debug for Lifetime {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
171 }
172 }
173
174 impl Lifetime {
is_elided(&self) -> bool175 pub fn is_elided(&self) -> bool {
176 self.name.is_elided()
177 }
178
is_static(&self) -> bool179 pub fn is_static(&self) -> bool {
180 self.name.is_static()
181 }
182 }
183
184 /// A `Path` is essentially Rust's notion of a name; for instance,
185 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
186 /// along with a bunch of supporting information.
187 #[derive(Debug, HashStable_Generic)]
188 pub struct Path<'hir> {
189 pub span: Span,
190 /// The resolution for the path.
191 pub res: Res,
192 /// The segments in the path: the things separated by `::`.
193 pub segments: &'hir [PathSegment<'hir>],
194 }
195
196 impl Path<'_> {
is_global(&self) -> bool197 pub fn is_global(&self) -> bool {
198 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
199 }
200 }
201
202 /// A segment of a path: an identifier, an optional lifetime, and a set of
203 /// types.
204 #[derive(Debug, HashStable_Generic)]
205 pub struct PathSegment<'hir> {
206 /// The identifier portion of this path segment.
207 #[stable_hasher(project(name))]
208 pub ident: Ident,
209 // `id` and `res` are optional. We currently only use these in save-analysis,
210 // any path segments without these will not have save-analysis info and
211 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
212 // affected. (In general, we don't bother to get the defs for synthesized
213 // segments, only for segments which have come from the AST).
214 pub hir_id: Option<HirId>,
215 pub res: Option<Res>,
216
217 /// Type/lifetime parameters attached to this path. They come in
218 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
219 /// this is more than just simple syntactic sugar; the use of
220 /// parens affects the region binding rules, so we preserve the
221 /// distinction.
222 pub args: Option<&'hir GenericArgs<'hir>>,
223
224 /// Whether to infer remaining type parameters, if any.
225 /// This only applies to expression and pattern paths, and
226 /// out of those only the segments with no type parameters
227 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
228 pub infer_args: bool,
229 }
230
231 impl<'hir> PathSegment<'hir> {
232 /// Converts an identifier to the corresponding segment.
from_ident(ident: Ident) -> PathSegment<'hir>233 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
234 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
235 }
236
invalid() -> Self237 pub fn invalid() -> Self {
238 Self::from_ident(Ident::empty())
239 }
240
args(&self) -> &GenericArgs<'hir>241 pub fn args(&self) -> &GenericArgs<'hir> {
242 if let Some(ref args) = self.args {
243 args
244 } else {
245 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
246 DUMMY
247 }
248 }
249 }
250
251 #[derive(Encodable, Debug, HashStable_Generic)]
252 pub struct ConstArg {
253 pub value: AnonConst,
254 pub span: Span,
255 }
256
257 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
258 pub enum InferKind {
259 Const,
260 Type,
261 }
262
263 impl InferKind {
264 #[inline]
is_type(self) -> bool265 pub fn is_type(self) -> bool {
266 matches!(self, InferKind::Type)
267 }
268 }
269
270 #[derive(Encodable, Debug, HashStable_Generic)]
271 pub struct InferArg {
272 pub hir_id: HirId,
273 pub kind: InferKind,
274 pub span: Span,
275 }
276
277 impl InferArg {
to_ty(&self) -> Ty<'_>278 pub fn to_ty(&self) -> Ty<'_> {
279 Ty { kind: TyKind::Infer, span: self.span, hir_id: self.hir_id }
280 }
281 }
282
283 #[derive(Debug, HashStable_Generic)]
284 pub enum GenericArg<'hir> {
285 Lifetime(Lifetime),
286 Type(Ty<'hir>),
287 Const(ConstArg),
288 Infer(InferArg),
289 }
290
291 impl GenericArg<'_> {
span(&self) -> Span292 pub fn span(&self) -> Span {
293 match self {
294 GenericArg::Lifetime(l) => l.span,
295 GenericArg::Type(t) => t.span,
296 GenericArg::Const(c) => c.span,
297 GenericArg::Infer(i) => i.span,
298 }
299 }
300
id(&self) -> HirId301 pub fn id(&self) -> HirId {
302 match self {
303 GenericArg::Lifetime(l) => l.hir_id,
304 GenericArg::Type(t) => t.hir_id,
305 GenericArg::Const(c) => c.value.hir_id,
306 GenericArg::Infer(i) => i.hir_id,
307 }
308 }
309
is_const(&self) -> bool310 pub fn is_const(&self) -> bool {
311 matches!(self, GenericArg::Const(_))
312 }
313
is_synthetic(&self) -> bool314 pub fn is_synthetic(&self) -> bool {
315 matches!(self, GenericArg::Lifetime(lifetime) if lifetime.name.ident() == Ident::empty())
316 }
317
descr(&self) -> &'static str318 pub fn descr(&self) -> &'static str {
319 match self {
320 GenericArg::Lifetime(_) => "lifetime",
321 GenericArg::Type(_) => "type",
322 GenericArg::Const(_) => "constant",
323 GenericArg::Infer(_) => "inferred",
324 }
325 }
326
to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd327 pub fn to_ord(&self, feats: &rustc_feature::Features) -> ast::ParamKindOrd {
328 match self {
329 GenericArg::Lifetime(_) => ast::ParamKindOrd::Lifetime,
330 GenericArg::Type(_) => ast::ParamKindOrd::Type,
331 GenericArg::Const(_) => {
332 ast::ParamKindOrd::Const { unordered: feats.unordered_const_ty_params() }
333 }
334 GenericArg::Infer(_) => ast::ParamKindOrd::Infer,
335 }
336 }
337 }
338
339 #[derive(Debug, HashStable_Generic)]
340 pub struct GenericArgs<'hir> {
341 /// The generic arguments for this path segment.
342 pub args: &'hir [GenericArg<'hir>],
343 /// Bindings (equality constraints) on associated types, if present.
344 /// E.g., `Foo<A = Bar>`.
345 pub bindings: &'hir [TypeBinding<'hir>],
346 /// Were arguments written in parenthesized form `Fn(T) -> U`?
347 /// This is required mostly for pretty-printing and diagnostics,
348 /// but also for changing lifetime elision rules to be "function-like".
349 pub parenthesized: bool,
350 /// The span encompassing arguments and the surrounding brackets `<>` or `()`
351 /// Foo<A, B, AssocTy = D> Fn(T, U, V) -> W
352 /// ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
353 /// Note that this may be:
354 /// - empty, if there are no generic brackets (but there may be hidden lifetimes)
355 /// - dummy, if this was generated while desugaring
356 pub span_ext: Span,
357 }
358
359 impl GenericArgs<'_> {
none() -> Self360 pub const fn none() -> Self {
361 Self { args: &[], bindings: &[], parenthesized: false, span_ext: DUMMY_SP }
362 }
363
inputs(&self) -> &[Ty<'_>]364 pub fn inputs(&self) -> &[Ty<'_>] {
365 if self.parenthesized {
366 for arg in self.args {
367 match arg {
368 GenericArg::Lifetime(_) => {}
369 GenericArg::Type(ref ty) => {
370 if let TyKind::Tup(ref tys) = ty.kind {
371 return tys;
372 }
373 break;
374 }
375 GenericArg::Const(_) => {}
376 GenericArg::Infer(_) => {}
377 }
378 }
379 }
380 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
381 }
382
383 #[inline]
has_type_params(&self) -> bool384 pub fn has_type_params(&self) -> bool {
385 self.args.iter().any(|arg| matches!(arg, GenericArg::Type(_)))
386 }
387
has_err(&self) -> bool388 pub fn has_err(&self) -> bool {
389 self.args.iter().any(|arg| match arg {
390 GenericArg::Type(ty) => matches!(ty.kind, TyKind::Err),
391 _ => false,
392 }) || self.bindings.iter().any(|arg| match arg.kind {
393 TypeBindingKind::Equality { ty } => matches!(ty.kind, TyKind::Err),
394 _ => false,
395 })
396 }
397
398 #[inline]
num_type_params(&self) -> usize399 pub fn num_type_params(&self) -> usize {
400 self.args.iter().filter(|arg| matches!(arg, GenericArg::Type(_))).count()
401 }
402
403 #[inline]
num_lifetime_params(&self) -> usize404 pub fn num_lifetime_params(&self) -> usize {
405 self.args.iter().filter(|arg| matches!(arg, GenericArg::Lifetime(_))).count()
406 }
407
408 #[inline]
has_lifetime_params(&self) -> bool409 pub fn has_lifetime_params(&self) -> bool {
410 self.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)))
411 }
412
413 #[inline]
num_generic_params(&self) -> usize414 pub fn num_generic_params(&self) -> usize {
415 self.args.iter().filter(|arg| !matches!(arg, GenericArg::Lifetime(_))).count()
416 }
417
418 /// The span encompassing the text inside the surrounding brackets.
419 /// It will also include bindings if they aren't in the form `-> Ret`
420 /// Returns `None` if the span is empty (e.g. no brackets) or dummy
span(&self) -> Option<Span>421 pub fn span(&self) -> Option<Span> {
422 let span_ext = self.span_ext()?;
423 Some(span_ext.with_lo(span_ext.lo() + BytePos(1)).with_hi(span_ext.hi() - BytePos(1)))
424 }
425
426 /// Returns span encompassing arguments and their surrounding `<>` or `()`
span_ext(&self) -> Option<Span>427 pub fn span_ext(&self) -> Option<Span> {
428 Some(self.span_ext).filter(|span| !span.is_empty())
429 }
430
is_empty(&self) -> bool431 pub fn is_empty(&self) -> bool {
432 self.args.is_empty()
433 }
434 }
435
436 /// A modifier on a bound, currently this is only used for `?Sized`, where the
437 /// modifier is `Maybe`. Negative bounds should also be handled here.
438 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
439 #[derive(HashStable_Generic)]
440 pub enum TraitBoundModifier {
441 None,
442 Maybe,
443 MaybeConst,
444 }
445
446 /// The AST represents all type param bounds as types.
447 /// `typeck::collect::compute_bounds` matches these against
448 /// the "special" built-in traits (see `middle::lang_items`) and
449 /// detects `Copy`, `Send` and `Sync`.
450 #[derive(Clone, Debug, HashStable_Generic)]
451 pub enum GenericBound<'hir> {
452 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
453 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
454 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
455 Outlives(Lifetime),
456 }
457
458 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
459 rustc_data_structures::static_assert_size!(GenericBound<'_>, 48);
460
461 impl GenericBound<'_> {
trait_ref(&self) -> Option<&TraitRef<'_>>462 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
463 match self {
464 GenericBound::Trait(data, _) => Some(&data.trait_ref),
465 _ => None,
466 }
467 }
468
span(&self) -> Span469 pub fn span(&self) -> Span {
470 match self {
471 GenericBound::Trait(t, ..) => t.span,
472 GenericBound::LangItemTrait(_, span, ..) => *span,
473 GenericBound::Outlives(l) => l.span,
474 }
475 }
476 }
477
478 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
479
480 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
481 pub enum LifetimeParamKind {
482 // Indicates that the lifetime definition was explicitly declared (e.g., in
483 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
484 Explicit,
485
486 // Indicates that the lifetime definition was synthetically added
487 // as a result of an in-band lifetime usage (e.g., in
488 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
489 InBand,
490
491 // Indication that the lifetime was elided (e.g., in both cases in
492 // `fn foo(x: &u8) -> &'_ u8 { x }`).
493 Elided,
494
495 // Indication that the lifetime name was somehow in error.
496 Error,
497 }
498
499 #[derive(Debug, HashStable_Generic)]
500 pub enum GenericParamKind<'hir> {
501 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
502 Lifetime {
503 kind: LifetimeParamKind,
504 },
505 Type {
506 default: Option<&'hir Ty<'hir>>,
507 synthetic: bool,
508 },
509 Const {
510 ty: &'hir Ty<'hir>,
511 /// Optional default value for the const generic param
512 default: Option<AnonConst>,
513 },
514 }
515
516 #[derive(Debug, HashStable_Generic)]
517 pub struct GenericParam<'hir> {
518 pub hir_id: HirId,
519 pub name: ParamName,
520 pub bounds: GenericBounds<'hir>,
521 pub span: Span,
522 pub pure_wrt_drop: bool,
523 pub kind: GenericParamKind<'hir>,
524 }
525
526 impl GenericParam<'hir> {
bounds_span(&self) -> Option<Span>527 pub fn bounds_span(&self) -> Option<Span> {
528 self.bounds.iter().fold(None, |span, bound| {
529 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
530
531 Some(span)
532 })
533 }
534 }
535
536 #[derive(Default)]
537 pub struct GenericParamCount {
538 pub lifetimes: usize,
539 pub types: usize,
540 pub consts: usize,
541 pub infer: usize,
542 }
543
544 /// Represents lifetimes and type parameters attached to a declaration
545 /// of a function, enum, trait, etc.
546 #[derive(Debug, HashStable_Generic)]
547 pub struct Generics<'hir> {
548 pub params: &'hir [GenericParam<'hir>],
549 pub where_clause: WhereClause<'hir>,
550 pub span: Span,
551 }
552
553 impl Generics<'hir> {
empty() -> Generics<'hir>554 pub const fn empty() -> Generics<'hir> {
555 Generics {
556 params: &[],
557 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
558 span: DUMMY_SP,
559 }
560 }
561
get_named(&self, name: Symbol) -> Option<&GenericParam<'_>>562 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
563 for param in self.params {
564 if name == param.name.ident().name {
565 return Some(param);
566 }
567 }
568 None
569 }
570
spans(&self) -> MultiSpan571 pub fn spans(&self) -> MultiSpan {
572 if self.params.is_empty() {
573 self.span.into()
574 } else {
575 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
576 }
577 }
578 }
579
580 /// A where-clause in a definition.
581 #[derive(Debug, HashStable_Generic)]
582 pub struct WhereClause<'hir> {
583 pub predicates: &'hir [WherePredicate<'hir>],
584 // Only valid if predicates aren't empty.
585 pub span: Span,
586 }
587
588 impl WhereClause<'_> {
span(&self) -> Option<Span>589 pub fn span(&self) -> Option<Span> {
590 if self.predicates.is_empty() { None } else { Some(self.span) }
591 }
592
593 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
594 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
span_for_predicates_or_empty_place(&self) -> Span595 pub fn span_for_predicates_or_empty_place(&self) -> Span {
596 self.span
597 }
598
599 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
600 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
tail_span_for_suggestion(&self) -> Span601 pub fn tail_span_for_suggestion(&self) -> Span {
602 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
603 self.predicates.last().map_or(end, |p| p.span()).shrink_to_hi().to(end)
604 }
605 }
606
607 /// A single predicate in a where-clause.
608 #[derive(Debug, HashStable_Generic)]
609 pub enum WherePredicate<'hir> {
610 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
611 BoundPredicate(WhereBoundPredicate<'hir>),
612 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
613 RegionPredicate(WhereRegionPredicate<'hir>),
614 /// An equality predicate (unsupported).
615 EqPredicate(WhereEqPredicate<'hir>),
616 }
617
618 impl WherePredicate<'_> {
span(&self) -> Span619 pub fn span(&self) -> Span {
620 match self {
621 WherePredicate::BoundPredicate(p) => p.span,
622 WherePredicate::RegionPredicate(p) => p.span,
623 WherePredicate::EqPredicate(p) => p.span,
624 }
625 }
626 }
627
628 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
629 #[derive(Debug, HashStable_Generic)]
630 pub struct WhereBoundPredicate<'hir> {
631 pub span: Span,
632 /// Any generics from a `for` binding.
633 pub bound_generic_params: &'hir [GenericParam<'hir>],
634 /// The type being bounded.
635 pub bounded_ty: &'hir Ty<'hir>,
636 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
637 pub bounds: GenericBounds<'hir>,
638 }
639
640 impl WhereBoundPredicate<'hir> {
641 /// Returns `true` if `param_def_id` matches the `bounded_ty` of this predicate.
is_param_bound(&self, param_def_id: DefId) -> bool642 pub fn is_param_bound(&self, param_def_id: DefId) -> bool {
643 let path = match self.bounded_ty.kind {
644 TyKind::Path(QPath::Resolved(None, path)) => path,
645 _ => return false,
646 };
647 match path.res {
648 Res::Def(DefKind::TyParam, def_id) | Res::SelfTy(Some(def_id), None) => {
649 def_id == param_def_id
650 }
651 _ => false,
652 }
653 }
654 }
655
656 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
657 #[derive(Debug, HashStable_Generic)]
658 pub struct WhereRegionPredicate<'hir> {
659 pub span: Span,
660 pub lifetime: Lifetime,
661 pub bounds: GenericBounds<'hir>,
662 }
663
664 /// An equality predicate (e.g., `T = int`); currently unsupported.
665 #[derive(Debug, HashStable_Generic)]
666 pub struct WhereEqPredicate<'hir> {
667 pub hir_id: HirId,
668 pub span: Span,
669 pub lhs_ty: &'hir Ty<'hir>,
670 pub rhs_ty: &'hir Ty<'hir>,
671 }
672
673 /// HIR node coupled with its parent's id in the same HIR owner.
674 ///
675 /// The parent is trash when the node is a HIR owner.
676 #[derive(Clone, Debug)]
677 pub struct ParentedNode<'tcx> {
678 pub parent: ItemLocalId,
679 pub node: Node<'tcx>,
680 }
681
682 /// Attributes owned by a HIR owner.
683 #[derive(Debug)]
684 pub struct AttributeMap<'tcx> {
685 pub map: SortedMap<ItemLocalId, &'tcx [Attribute]>,
686 pub hash: Fingerprint,
687 }
688
689 impl<'tcx> AttributeMap<'tcx> {
690 pub const EMPTY: &'static AttributeMap<'static> =
691 &AttributeMap { map: SortedMap::new(), hash: Fingerprint::ZERO };
692
693 #[inline]
get(&self, id: ItemLocalId) -> &'tcx [Attribute]694 pub fn get(&self, id: ItemLocalId) -> &'tcx [Attribute] {
695 self.map.get(&id).copied().unwrap_or(&[])
696 }
697 }
698
699 /// Map of all HIR nodes inside the current owner.
700 /// These nodes are mapped by `ItemLocalId` alongside the index of their parent node.
701 /// The HIR tree, including bodies, is pre-hashed.
702 #[derive(Debug)]
703 pub struct OwnerNodes<'tcx> {
704 /// Pre-computed hash of the full HIR.
705 pub hash_including_bodies: Fingerprint,
706 /// Pre-computed hash of the item signature, sithout recursing into the body.
707 pub hash_without_bodies: Fingerprint,
708 /// Full HIR for the current owner.
709 // The zeroth node's parent should never be accessed: the owner's parent is computed by the
710 // hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
711 // used.
712 pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
713 /// Content of local bodies.
714 pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
715 }
716
717 /// Full information resulting from lowering an AST node.
718 #[derive(Debug, HashStable_Generic)]
719 pub struct OwnerInfo<'hir> {
720 /// Contents of the HIR.
721 pub nodes: OwnerNodes<'hir>,
722 /// Map from each nested owner to its parent's local id.
723 pub parenting: FxHashMap<LocalDefId, ItemLocalId>,
724 /// Collected attributes of the HIR nodes.
725 pub attrs: AttributeMap<'hir>,
726 /// Map indicating what traits are in scope for places where this
727 /// is relevant; generated by resolve.
728 pub trait_map: FxHashMap<ItemLocalId, Box<[TraitCandidate]>>,
729 }
730
731 impl<'tcx> OwnerInfo<'tcx> {
732 #[inline]
node(&self) -> OwnerNode<'tcx>733 pub fn node(&self) -> OwnerNode<'tcx> {
734 use rustc_index::vec::Idx;
735 let node = self.nodes.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
736 let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
737 node
738 }
739 }
740
741 /// The top-level data structure that stores the entire contents of
742 /// the crate currently being compiled.
743 ///
744 /// For more details, see the [rustc dev guide].
745 ///
746 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
747 #[derive(Debug)]
748 pub struct Crate<'hir> {
749 pub owners: IndexVec<LocalDefId, Option<OwnerInfo<'hir>>>,
750 pub hir_hash: Fingerprint,
751 }
752
753 /// A block of statements `{ .. }`, which may have a label (in this case the
754 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
755 /// the `rules` being anything but `DefaultBlock`.
756 #[derive(Debug, HashStable_Generic)]
757 pub struct Block<'hir> {
758 /// Statements in a block.
759 pub stmts: &'hir [Stmt<'hir>],
760 /// An expression at the end of the block
761 /// without a semicolon, if any.
762 pub expr: Option<&'hir Expr<'hir>>,
763 #[stable_hasher(ignore)]
764 pub hir_id: HirId,
765 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
766 pub rules: BlockCheckMode,
767 pub span: Span,
768 /// If true, then there may exist `break 'a` values that aim to
769 /// break out of this block early.
770 /// Used by `'label: {}` blocks and by `try {}` blocks.
771 pub targeted_by_break: bool,
772 }
773
774 #[derive(Debug, HashStable_Generic)]
775 pub struct Pat<'hir> {
776 #[stable_hasher(ignore)]
777 pub hir_id: HirId,
778 pub kind: PatKind<'hir>,
779 pub span: Span,
780 // Whether to use default binding modes.
781 // At present, this is false only for destructuring assignment.
782 pub default_binding_modes: bool,
783 }
784
785 impl<'hir> Pat<'hir> {
786 // FIXME(#19596) this is a workaround, but there should be a better way
walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool787 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) -> bool {
788 if !it(self) {
789 return false;
790 }
791
792 use PatKind::*;
793 match self.kind {
794 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
795 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
796 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
797 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
798 Slice(before, slice, after) => {
799 before.iter().chain(slice).chain(after.iter()).all(|p| p.walk_short_(it))
800 }
801 }
802 }
803
804 /// Walk the pattern in left-to-right order,
805 /// short circuiting (with `.all(..)`) if `false` is returned.
806 ///
807 /// Note that when visiting e.g. `Tuple(ps)`,
808 /// if visiting `ps[0]` returns `false`,
809 /// then `ps[1]` will not be visited.
walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool810 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) -> bool {
811 self.walk_short_(&mut it)
812 }
813
814 // FIXME(#19596) this is a workaround, but there should be a better way
walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool)815 fn walk_(&self, it: &mut impl FnMut(&Pat<'hir>) -> bool) {
816 if !it(self) {
817 return;
818 }
819
820 use PatKind::*;
821 match self.kind {
822 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
823 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
824 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
825 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
826 Slice(before, slice, after) => {
827 before.iter().chain(slice).chain(after.iter()).for_each(|p| p.walk_(it))
828 }
829 }
830 }
831
832 /// Walk the pattern in left-to-right order.
833 ///
834 /// If `it(pat)` returns `false`, the children are not visited.
walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool)835 pub fn walk(&self, mut it: impl FnMut(&Pat<'hir>) -> bool) {
836 self.walk_(&mut it)
837 }
838
839 /// Walk the pattern in left-to-right order.
840 ///
841 /// If you always want to recurse, prefer this method over `walk`.
walk_always(&self, mut it: impl FnMut(&Pat<'_>))842 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
843 self.walk(|p| {
844 it(p);
845 true
846 })
847 }
848 }
849
850 /// A single field in a struct pattern.
851 ///
852 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
853 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
854 /// except `is_shorthand` is true.
855 #[derive(Debug, HashStable_Generic)]
856 pub struct PatField<'hir> {
857 #[stable_hasher(ignore)]
858 pub hir_id: HirId,
859 /// The identifier for the field.
860 #[stable_hasher(project(name))]
861 pub ident: Ident,
862 /// The pattern the field is destructured to.
863 pub pat: &'hir Pat<'hir>,
864 pub is_shorthand: bool,
865 pub span: Span,
866 }
867
868 /// Explicit binding annotations given in the HIR for a binding. Note
869 /// that this is not the final binding *mode* that we infer after type
870 /// inference.
871 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
872 pub enum BindingAnnotation {
873 /// No binding annotation given: this means that the final binding mode
874 /// will depend on whether we have skipped through a `&` reference
875 /// when matching. For example, the `x` in `Some(x)` will have binding
876 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
877 /// ultimately be inferred to be by-reference.
878 ///
879 /// Note that implicit reference skipping is not implemented yet (#42640).
880 Unannotated,
881
882 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
883 Mutable,
884
885 /// Annotated as `ref`, like `ref x`
886 Ref,
887
888 /// Annotated as `ref mut x`.
889 RefMut,
890 }
891
892 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
893 pub enum RangeEnd {
894 Included,
895 Excluded,
896 }
897
898 impl fmt::Display for RangeEnd {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 f.write_str(match self {
901 RangeEnd::Included => "..=",
902 RangeEnd::Excluded => "..",
903 })
904 }
905 }
906
907 #[derive(Debug, HashStable_Generic)]
908 pub enum PatKind<'hir> {
909 /// Represents a wildcard pattern (i.e., `_`).
910 Wild,
911
912 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
913 /// The `HirId` is the canonical ID for the variable being bound,
914 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
915 /// which is the pattern ID of the first `x`.
916 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
917
918 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
919 /// The `bool` is `true` in the presence of a `..`.
920 Struct(QPath<'hir>, &'hir [PatField<'hir>], bool),
921
922 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
923 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
924 /// `0 <= position <= subpats.len()`
925 TupleStruct(QPath<'hir>, &'hir [Pat<'hir>], Option<usize>),
926
927 /// An or-pattern `A | B | C`.
928 /// Invariant: `pats.len() >= 2`.
929 Or(&'hir [Pat<'hir>]),
930
931 /// A path pattern for a unit struct/variant or a (maybe-associated) constant.
932 Path(QPath<'hir>),
933
934 /// A tuple pattern (e.g., `(a, b)`).
935 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
936 /// `0 <= position <= subpats.len()`
937 Tuple(&'hir [Pat<'hir>], Option<usize>),
938
939 /// A `box` pattern.
940 Box(&'hir Pat<'hir>),
941
942 /// A reference pattern (e.g., `&mut (a, b)`).
943 Ref(&'hir Pat<'hir>, Mutability),
944
945 /// A literal.
946 Lit(&'hir Expr<'hir>),
947
948 /// A range pattern (e.g., `1..=2` or `1..2`).
949 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
950
951 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
952 ///
953 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
954 /// If `slice` exists, then `after` can be non-empty.
955 ///
956 /// The representation for e.g., `[a, b, .., c, d]` is:
957 /// ```
958 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
959 /// ```
960 Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]),
961 }
962
963 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
964 pub enum BinOpKind {
965 /// The `+` operator (addition).
966 Add,
967 /// The `-` operator (subtraction).
968 Sub,
969 /// The `*` operator (multiplication).
970 Mul,
971 /// The `/` operator (division).
972 Div,
973 /// The `%` operator (modulus).
974 Rem,
975 /// The `&&` operator (logical and).
976 And,
977 /// The `||` operator (logical or).
978 Or,
979 /// The `^` operator (bitwise xor).
980 BitXor,
981 /// The `&` operator (bitwise and).
982 BitAnd,
983 /// The `|` operator (bitwise or).
984 BitOr,
985 /// The `<<` operator (shift left).
986 Shl,
987 /// The `>>` operator (shift right).
988 Shr,
989 /// The `==` operator (equality).
990 Eq,
991 /// The `<` operator (less than).
992 Lt,
993 /// The `<=` operator (less than or equal to).
994 Le,
995 /// The `!=` operator (not equal to).
996 Ne,
997 /// The `>=` operator (greater than or equal to).
998 Ge,
999 /// The `>` operator (greater than).
1000 Gt,
1001 }
1002
1003 impl BinOpKind {
as_str(self) -> &'static str1004 pub fn as_str(self) -> &'static str {
1005 match self {
1006 BinOpKind::Add => "+",
1007 BinOpKind::Sub => "-",
1008 BinOpKind::Mul => "*",
1009 BinOpKind::Div => "/",
1010 BinOpKind::Rem => "%",
1011 BinOpKind::And => "&&",
1012 BinOpKind::Or => "||",
1013 BinOpKind::BitXor => "^",
1014 BinOpKind::BitAnd => "&",
1015 BinOpKind::BitOr => "|",
1016 BinOpKind::Shl => "<<",
1017 BinOpKind::Shr => ">>",
1018 BinOpKind::Eq => "==",
1019 BinOpKind::Lt => "<",
1020 BinOpKind::Le => "<=",
1021 BinOpKind::Ne => "!=",
1022 BinOpKind::Ge => ">=",
1023 BinOpKind::Gt => ">",
1024 }
1025 }
1026
is_lazy(self) -> bool1027 pub fn is_lazy(self) -> bool {
1028 matches!(self, BinOpKind::And | BinOpKind::Or)
1029 }
1030
is_shift(self) -> bool1031 pub fn is_shift(self) -> bool {
1032 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
1033 }
1034
is_comparison(self) -> bool1035 pub fn is_comparison(self) -> bool {
1036 match self {
1037 BinOpKind::Eq
1038 | BinOpKind::Lt
1039 | BinOpKind::Le
1040 | BinOpKind::Ne
1041 | BinOpKind::Gt
1042 | BinOpKind::Ge => true,
1043 BinOpKind::And
1044 | BinOpKind::Or
1045 | BinOpKind::Add
1046 | BinOpKind::Sub
1047 | BinOpKind::Mul
1048 | BinOpKind::Div
1049 | BinOpKind::Rem
1050 | BinOpKind::BitXor
1051 | BinOpKind::BitAnd
1052 | BinOpKind::BitOr
1053 | BinOpKind::Shl
1054 | BinOpKind::Shr => false,
1055 }
1056 }
1057
1058 /// Returns `true` if the binary operator takes its arguments by value.
is_by_value(self) -> bool1059 pub fn is_by_value(self) -> bool {
1060 !self.is_comparison()
1061 }
1062 }
1063
1064 impl Into<ast::BinOpKind> for BinOpKind {
into(self) -> ast::BinOpKind1065 fn into(self) -> ast::BinOpKind {
1066 match self {
1067 BinOpKind::Add => ast::BinOpKind::Add,
1068 BinOpKind::Sub => ast::BinOpKind::Sub,
1069 BinOpKind::Mul => ast::BinOpKind::Mul,
1070 BinOpKind::Div => ast::BinOpKind::Div,
1071 BinOpKind::Rem => ast::BinOpKind::Rem,
1072 BinOpKind::And => ast::BinOpKind::And,
1073 BinOpKind::Or => ast::BinOpKind::Or,
1074 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1075 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1076 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1077 BinOpKind::Shl => ast::BinOpKind::Shl,
1078 BinOpKind::Shr => ast::BinOpKind::Shr,
1079 BinOpKind::Eq => ast::BinOpKind::Eq,
1080 BinOpKind::Lt => ast::BinOpKind::Lt,
1081 BinOpKind::Le => ast::BinOpKind::Le,
1082 BinOpKind::Ne => ast::BinOpKind::Ne,
1083 BinOpKind::Ge => ast::BinOpKind::Ge,
1084 BinOpKind::Gt => ast::BinOpKind::Gt,
1085 }
1086 }
1087 }
1088
1089 pub type BinOp = Spanned<BinOpKind>;
1090
1091 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1092 pub enum UnOp {
1093 /// The `*` operator (deferencing).
1094 Deref,
1095 /// The `!` operator (logical negation).
1096 Not,
1097 /// The `-` operator (negation).
1098 Neg,
1099 }
1100
1101 impl UnOp {
as_str(self) -> &'static str1102 pub fn as_str(self) -> &'static str {
1103 match self {
1104 Self::Deref => "*",
1105 Self::Not => "!",
1106 Self::Neg => "-",
1107 }
1108 }
1109
1110 /// Returns `true` if the unary operator takes its argument by value.
is_by_value(self) -> bool1111 pub fn is_by_value(self) -> bool {
1112 matches!(self, Self::Neg | Self::Not)
1113 }
1114 }
1115
1116 /// A statement.
1117 #[derive(Debug, HashStable_Generic)]
1118 pub struct Stmt<'hir> {
1119 pub hir_id: HirId,
1120 pub kind: StmtKind<'hir>,
1121 pub span: Span,
1122 }
1123
1124 /// The contents of a statement.
1125 #[derive(Debug, HashStable_Generic)]
1126 pub enum StmtKind<'hir> {
1127 /// A local (`let`) binding.
1128 Local(&'hir Local<'hir>),
1129
1130 /// An item binding.
1131 Item(ItemId),
1132
1133 /// An expression without a trailing semi-colon (must have unit type).
1134 Expr(&'hir Expr<'hir>),
1135
1136 /// An expression with a trailing semi-colon (may have any type).
1137 Semi(&'hir Expr<'hir>),
1138 }
1139
1140 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1141 #[derive(Debug, HashStable_Generic)]
1142 pub struct Local<'hir> {
1143 pub pat: &'hir Pat<'hir>,
1144 /// Type annotation, if any (otherwise the type will be inferred).
1145 pub ty: Option<&'hir Ty<'hir>>,
1146 /// Initializer expression to set the value, if any.
1147 pub init: Option<&'hir Expr<'hir>>,
1148 pub hir_id: HirId,
1149 pub span: Span,
1150 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1151 /// desugaring. Otherwise will be `Normal`.
1152 pub source: LocalSource,
1153 }
1154
1155 /// Represents a single arm of a `match` expression, e.g.
1156 /// `<pat> (if <guard>) => <body>`.
1157 #[derive(Debug, HashStable_Generic)]
1158 pub struct Arm<'hir> {
1159 #[stable_hasher(ignore)]
1160 pub hir_id: HirId,
1161 pub span: Span,
1162 /// If this pattern and the optional guard matches, then `body` is evaluated.
1163 pub pat: &'hir Pat<'hir>,
1164 /// Optional guard clause.
1165 pub guard: Option<Guard<'hir>>,
1166 /// The expression the arm evaluates to if this arm matches.
1167 pub body: &'hir Expr<'hir>,
1168 }
1169
1170 #[derive(Debug, HashStable_Generic)]
1171 pub enum Guard<'hir> {
1172 If(&'hir Expr<'hir>),
1173 // FIXME use ExprKind::Let for this.
1174 IfLet(&'hir Pat<'hir>, &'hir Expr<'hir>),
1175 }
1176
1177 #[derive(Debug, HashStable_Generic)]
1178 pub struct ExprField<'hir> {
1179 #[stable_hasher(ignore)]
1180 pub hir_id: HirId,
1181 pub ident: Ident,
1182 pub expr: &'hir Expr<'hir>,
1183 pub span: Span,
1184 pub is_shorthand: bool,
1185 }
1186
1187 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1188 pub enum BlockCheckMode {
1189 DefaultBlock,
1190 UnsafeBlock(UnsafeSource),
1191 }
1192
1193 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1194 pub enum UnsafeSource {
1195 CompilerGenerated,
1196 UserProvided,
1197 }
1198
1199 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1200 pub struct BodyId {
1201 pub hir_id: HirId,
1202 }
1203
1204 /// The body of a function, closure, or constant value. In the case of
1205 /// a function, the body contains not only the function body itself
1206 /// (which is an expression), but also the argument patterns, since
1207 /// those are something that the caller doesn't really care about.
1208 ///
1209 /// # Examples
1210 ///
1211 /// ```
1212 /// fn foo((x, y): (u32, u32)) -> u32 {
1213 /// x + y
1214 /// }
1215 /// ```
1216 ///
1217 /// Here, the `Body` associated with `foo()` would contain:
1218 ///
1219 /// - an `params` array containing the `(x, y)` pattern
1220 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1221 /// - `generator_kind` would be `None`
1222 ///
1223 /// All bodies have an **owner**, which can be accessed via the HIR
1224 /// map using `body_owner_def_id()`.
1225 #[derive(Debug)]
1226 pub struct Body<'hir> {
1227 pub params: &'hir [Param<'hir>],
1228 pub value: Expr<'hir>,
1229 pub generator_kind: Option<GeneratorKind>,
1230 }
1231
1232 impl Body<'hir> {
id(&self) -> BodyId1233 pub fn id(&self) -> BodyId {
1234 BodyId { hir_id: self.value.hir_id }
1235 }
1236
generator_kind(&self) -> Option<GeneratorKind>1237 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1238 self.generator_kind
1239 }
1240 }
1241
1242 /// The type of source expression that caused this generator to be created.
1243 #[derive(
1244 Clone,
1245 PartialEq,
1246 PartialOrd,
1247 Eq,
1248 Hash,
1249 HashStable_Generic,
1250 Encodable,
1251 Decodable,
1252 Debug,
1253 Copy
1254 )]
1255 pub enum GeneratorKind {
1256 /// An explicit `async` block or the body of an async function.
1257 Async(AsyncGeneratorKind),
1258
1259 /// A generator literal created via a `yield` inside a closure.
1260 Gen,
1261 }
1262
1263 impl fmt::Display for GeneratorKind {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1265 match self {
1266 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1267 GeneratorKind::Gen => f.write_str("generator"),
1268 }
1269 }
1270 }
1271
1272 impl GeneratorKind {
descr(&self) -> &'static str1273 pub fn descr(&self) -> &'static str {
1274 match self {
1275 GeneratorKind::Async(ask) => ask.descr(),
1276 GeneratorKind::Gen => "generator",
1277 }
1278 }
1279 }
1280
1281 /// In the case of a generator created as part of an async construct,
1282 /// which kind of async construct caused it to be created?
1283 ///
1284 /// This helps error messages but is also used to drive coercions in
1285 /// type-checking (see #60424).
1286 #[derive(
1287 Clone,
1288 PartialEq,
1289 PartialOrd,
1290 Eq,
1291 Hash,
1292 HashStable_Generic,
1293 Encodable,
1294 Decodable,
1295 Debug,
1296 Copy
1297 )]
1298 pub enum AsyncGeneratorKind {
1299 /// An explicit `async` block written by the user.
1300 Block,
1301
1302 /// An explicit `async` block written by the user.
1303 Closure,
1304
1305 /// The `async` block generated as the body of an async function.
1306 Fn,
1307 }
1308
1309 impl fmt::Display for AsyncGeneratorKind {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1311 f.write_str(match self {
1312 AsyncGeneratorKind::Block => "`async` block",
1313 AsyncGeneratorKind::Closure => "`async` closure body",
1314 AsyncGeneratorKind::Fn => "`async fn` body",
1315 })
1316 }
1317 }
1318
1319 impl AsyncGeneratorKind {
descr(&self) -> &'static str1320 pub fn descr(&self) -> &'static str {
1321 match self {
1322 AsyncGeneratorKind::Block => "`async` block",
1323 AsyncGeneratorKind::Closure => "`async` closure body",
1324 AsyncGeneratorKind::Fn => "`async fn` body",
1325 }
1326 }
1327 }
1328
1329 #[derive(Copy, Clone, Debug)]
1330 pub enum BodyOwnerKind {
1331 /// Functions and methods.
1332 Fn,
1333
1334 /// Closures
1335 Closure,
1336
1337 /// Constants and associated constants.
1338 Const,
1339
1340 /// Initializer of a `static` item.
1341 Static(Mutability),
1342 }
1343
1344 impl BodyOwnerKind {
is_fn_or_closure(self) -> bool1345 pub fn is_fn_or_closure(self) -> bool {
1346 match self {
1347 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1348 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1349 }
1350 }
1351 }
1352
1353 /// The kind of an item that requires const-checking.
1354 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1355 pub enum ConstContext {
1356 /// A `const fn`.
1357 ConstFn,
1358
1359 /// A `static` or `static mut`.
1360 Static(Mutability),
1361
1362 /// A `const`, associated `const`, or other const context.
1363 ///
1364 /// Other contexts include:
1365 /// - Array length expressions
1366 /// - Enum discriminants
1367 /// - Const generics
1368 ///
1369 /// For the most part, other contexts are treated just like a regular `const`, so they are
1370 /// lumped into the same category.
1371 Const,
1372 }
1373
1374 impl ConstContext {
1375 /// A description of this const context that can appear between backticks in an error message.
1376 ///
1377 /// E.g. `const` or `static mut`.
keyword_name(self) -> &'static str1378 pub fn keyword_name(self) -> &'static str {
1379 match self {
1380 Self::Const => "const",
1381 Self::Static(Mutability::Not) => "static",
1382 Self::Static(Mutability::Mut) => "static mut",
1383 Self::ConstFn => "const fn",
1384 }
1385 }
1386 }
1387
1388 /// A colloquial, trivially pluralizable description of this const context for use in error
1389 /// messages.
1390 impl fmt::Display for ConstContext {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1392 match *self {
1393 Self::Const => write!(f, "constant"),
1394 Self::Static(_) => write!(f, "static"),
1395 Self::ConstFn => write!(f, "constant function"),
1396 }
1397 }
1398 }
1399
1400 /// A literal.
1401 pub type Lit = Spanned<LitKind>;
1402
1403 /// A constant (expression) that's not an item or associated item,
1404 /// but needs its own `DefId` for type-checking, const-eval, etc.
1405 /// These are usually found nested inside types (e.g., array lengths)
1406 /// or expressions (e.g., repeat counts), and also used to define
1407 /// explicit discriminant values for enum variants.
1408 ///
1409 /// You can check if this anon const is a default in a const param
1410 /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_hir_id(..)`
1411 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1412 pub struct AnonConst {
1413 pub hir_id: HirId,
1414 pub body: BodyId,
1415 }
1416
1417 /// An expression.
1418 #[derive(Debug)]
1419 pub struct Expr<'hir> {
1420 pub hir_id: HirId,
1421 pub kind: ExprKind<'hir>,
1422 pub span: Span,
1423 }
1424
1425 impl Expr<'_> {
precedence(&self) -> ExprPrecedence1426 pub fn precedence(&self) -> ExprPrecedence {
1427 match self.kind {
1428 ExprKind::Box(_) => ExprPrecedence::Box,
1429 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1430 ExprKind::Array(_) => ExprPrecedence::Array,
1431 ExprKind::Call(..) => ExprPrecedence::Call,
1432 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1433 ExprKind::Tup(_) => ExprPrecedence::Tup,
1434 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1435 ExprKind::Unary(..) => ExprPrecedence::Unary,
1436 ExprKind::Lit(_) => ExprPrecedence::Lit,
1437 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1438 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1439 ExprKind::If(..) => ExprPrecedence::If,
1440 ExprKind::Let(..) => ExprPrecedence::Let,
1441 ExprKind::Loop(..) => ExprPrecedence::Loop,
1442 ExprKind::Match(..) => ExprPrecedence::Match,
1443 ExprKind::Closure(..) => ExprPrecedence::Closure,
1444 ExprKind::Block(..) => ExprPrecedence::Block,
1445 ExprKind::Assign(..) => ExprPrecedence::Assign,
1446 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1447 ExprKind::Field(..) => ExprPrecedence::Field,
1448 ExprKind::Index(..) => ExprPrecedence::Index,
1449 ExprKind::Path(..) => ExprPrecedence::Path,
1450 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1451 ExprKind::Break(..) => ExprPrecedence::Break,
1452 ExprKind::Continue(..) => ExprPrecedence::Continue,
1453 ExprKind::Ret(..) => ExprPrecedence::Ret,
1454 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1455 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1456 ExprKind::Struct(..) => ExprPrecedence::Struct,
1457 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1458 ExprKind::Yield(..) => ExprPrecedence::Yield,
1459 ExprKind::Err => ExprPrecedence::Err,
1460 }
1461 }
1462
1463 // Whether this looks like a place expr, without checking for deref
1464 // adjustments.
1465 // This will return `true` in some potentially surprising cases such as
1466 // `CONSTANT.field`.
is_syntactic_place_expr(&self) -> bool1467 pub fn is_syntactic_place_expr(&self) -> bool {
1468 self.is_place_expr(|_| true)
1469 }
1470
1471 /// Whether this is a place expression.
1472 ///
1473 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1474 /// on the given expression should be considered a place expression.
is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool1475 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1476 match self.kind {
1477 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1478 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1479 }
1480
1481 // Type ascription inherits its place expression kind from its
1482 // operand. See:
1483 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1484 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1485
1486 ExprKind::Unary(UnOp::Deref, _) => true,
1487
1488 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1489 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1490 }
1491
1492 // Lang item paths cannot currently be local variables or statics.
1493 ExprKind::Path(QPath::LangItem(..)) => false,
1494
1495 // Partially qualified paths in expressions can only legally
1496 // refer to associated items which are always rvalues.
1497 ExprKind::Path(QPath::TypeRelative(..))
1498 | ExprKind::Call(..)
1499 | ExprKind::MethodCall(..)
1500 | ExprKind::Struct(..)
1501 | ExprKind::Tup(..)
1502 | ExprKind::If(..)
1503 | ExprKind::Match(..)
1504 | ExprKind::Closure(..)
1505 | ExprKind::Block(..)
1506 | ExprKind::Repeat(..)
1507 | ExprKind::Array(..)
1508 | ExprKind::Break(..)
1509 | ExprKind::Continue(..)
1510 | ExprKind::Ret(..)
1511 | ExprKind::Let(..)
1512 | ExprKind::Loop(..)
1513 | ExprKind::Assign(..)
1514 | ExprKind::InlineAsm(..)
1515 | ExprKind::LlvmInlineAsm(..)
1516 | ExprKind::AssignOp(..)
1517 | ExprKind::Lit(_)
1518 | ExprKind::ConstBlock(..)
1519 | ExprKind::Unary(..)
1520 | ExprKind::Box(..)
1521 | ExprKind::AddrOf(..)
1522 | ExprKind::Binary(..)
1523 | ExprKind::Yield(..)
1524 | ExprKind::Cast(..)
1525 | ExprKind::DropTemps(..)
1526 | ExprKind::Err => false,
1527 }
1528 }
1529
1530 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1531 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1532 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1533 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1534 /// beyond remembering to call this function before doing analysis on it.
peel_drop_temps(&self) -> &Self1535 pub fn peel_drop_temps(&self) -> &Self {
1536 let mut expr = self;
1537 while let ExprKind::DropTemps(inner) = &expr.kind {
1538 expr = inner;
1539 }
1540 expr
1541 }
1542
peel_blocks(&self) -> &Self1543 pub fn peel_blocks(&self) -> &Self {
1544 let mut expr = self;
1545 while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind {
1546 expr = inner;
1547 }
1548 expr
1549 }
1550
can_have_side_effects(&self) -> bool1551 pub fn can_have_side_effects(&self) -> bool {
1552 match self.peel_drop_temps().kind {
1553 ExprKind::Path(_) | ExprKind::Lit(_) => false,
1554 ExprKind::Type(base, _)
1555 | ExprKind::Unary(_, base)
1556 | ExprKind::Field(base, _)
1557 | ExprKind::Index(base, _)
1558 | ExprKind::AddrOf(.., base)
1559 | ExprKind::Cast(base, _) => {
1560 // This isn't exactly true for `Index` and all `Unnary`, but we are using this
1561 // method exclusively for diagnostics and there's a *cultural* pressure against
1562 // them being used only for its side-effects.
1563 base.can_have_side_effects()
1564 }
1565 ExprKind::Struct(_, fields, init) => fields
1566 .iter()
1567 .map(|field| field.expr)
1568 .chain(init.into_iter())
1569 .all(|e| e.can_have_side_effects()),
1570
1571 ExprKind::Array(args)
1572 | ExprKind::Tup(args)
1573 | ExprKind::Call(
1574 Expr {
1575 kind:
1576 ExprKind::Path(QPath::Resolved(
1577 None,
1578 Path { res: Res::Def(DefKind::Ctor(_, CtorKind::Fn), _), .. },
1579 )),
1580 ..
1581 },
1582 args,
1583 ) => args.iter().all(|arg| arg.can_have_side_effects()),
1584 ExprKind::If(..)
1585 | ExprKind::Match(..)
1586 | ExprKind::MethodCall(..)
1587 | ExprKind::Call(..)
1588 | ExprKind::Closure(..)
1589 | ExprKind::Block(..)
1590 | ExprKind::Repeat(..)
1591 | ExprKind::Break(..)
1592 | ExprKind::Continue(..)
1593 | ExprKind::Ret(..)
1594 | ExprKind::Let(..)
1595 | ExprKind::Loop(..)
1596 | ExprKind::Assign(..)
1597 | ExprKind::InlineAsm(..)
1598 | ExprKind::LlvmInlineAsm(..)
1599 | ExprKind::AssignOp(..)
1600 | ExprKind::ConstBlock(..)
1601 | ExprKind::Box(..)
1602 | ExprKind::Binary(..)
1603 | ExprKind::Yield(..)
1604 | ExprKind::DropTemps(..)
1605 | ExprKind::Err => true,
1606 }
1607 }
1608 }
1609
1610 /// Checks if the specified expression is a built-in range literal.
1611 /// (See: `LoweringContext::lower_expr()`).
is_range_literal(expr: &Expr<'_>) -> bool1612 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1613 match expr.kind {
1614 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1615 ExprKind::Struct(ref qpath, _, _) => matches!(
1616 **qpath,
1617 QPath::LangItem(
1618 LangItem::Range
1619 | LangItem::RangeTo
1620 | LangItem::RangeFrom
1621 | LangItem::RangeFull
1622 | LangItem::RangeToInclusive,
1623 _,
1624 )
1625 ),
1626
1627 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1628 ExprKind::Call(ref func, _) => {
1629 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1630 }
1631
1632 _ => false,
1633 }
1634 }
1635
1636 #[derive(Debug, HashStable_Generic)]
1637 pub enum ExprKind<'hir> {
1638 /// A `box x` expression.
1639 Box(&'hir Expr<'hir>),
1640 /// Allow anonymous constants from an inline `const` block
1641 ConstBlock(AnonConst),
1642 /// An array (e.g., `[a, b, c, d]`).
1643 Array(&'hir [Expr<'hir>]),
1644 /// A function call.
1645 ///
1646 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1647 /// and the second field is the list of arguments.
1648 /// This also represents calling the constructor of
1649 /// tuple-like ADTs such as tuple structs and enum variants.
1650 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1651 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1652 ///
1653 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1654 /// (within the angle brackets).
1655 /// The first element of the vector of `Expr`s is the expression that evaluates
1656 /// to the object on which the method is being called on (the receiver),
1657 /// and the remaining elements are the rest of the arguments.
1658 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1659 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1660 /// The final `Span` represents the span of the function and arguments
1661 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1662 ///
1663 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1664 /// the `hir_id` of the `MethodCall` node itself.
1665 ///
1666 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1667 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1668 /// A tuple (e.g., `(a, b, c, d)`).
1669 Tup(&'hir [Expr<'hir>]),
1670 /// A binary operation (e.g., `a + b`, `a * b`).
1671 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1672 /// A unary operation (e.g., `!x`, `*x`).
1673 Unary(UnOp, &'hir Expr<'hir>),
1674 /// A literal (e.g., `1`, `"foo"`).
1675 Lit(Lit),
1676 /// A cast (e.g., `foo as f64`).
1677 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1678 /// A type reference (e.g., `Foo`).
1679 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1680 /// Wraps the expression in a terminating scope.
1681 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1682 ///
1683 /// This construct only exists to tweak the drop order in HIR lowering.
1684 /// An example of that is the desugaring of `for` loops.
1685 DropTemps(&'hir Expr<'hir>),
1686 /// A `let $pat = $expr` expression.
1687 ///
1688 /// These are not `Local` and only occur as expressions.
1689 /// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
1690 Let(&'hir Pat<'hir>, &'hir Expr<'hir>, Span),
1691 /// An `if` block, with an optional else block.
1692 ///
1693 /// I.e., `if <expr> { <expr> } else { <expr> }`.
1694 If(&'hir Expr<'hir>, &'hir Expr<'hir>, Option<&'hir Expr<'hir>>),
1695 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1696 ///
1697 /// I.e., `'label: loop { <block> }`.
1698 ///
1699 /// The `Span` is the loop header (`for x in y`/`while let pat = expr`).
1700 Loop(&'hir Block<'hir>, Option<Label>, LoopSource, Span),
1701 /// A `match` block, with a source that indicates whether or not it is
1702 /// the result of a desugaring, and if so, which kind.
1703 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1704 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1705 ///
1706 /// The `Span` is the argument block `|...|`.
1707 ///
1708 /// This may also be a generator literal or an `async block` as indicated by the
1709 /// `Option<Movability>`.
1710 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1711 /// A block (e.g., `'label: { ... }`).
1712 Block(&'hir Block<'hir>, Option<Label>),
1713
1714 /// An assignment (e.g., `a = foo()`).
1715 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1716 /// An assignment with an operator.
1717 ///
1718 /// E.g., `a += 1`.
1719 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1720 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1721 Field(&'hir Expr<'hir>, Ident),
1722 /// An indexing operation (`foo[2]`).
1723 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1724
1725 /// Path to a definition, possibly containing lifetime or type parameters.
1726 Path(QPath<'hir>),
1727
1728 /// A referencing operation (i.e., `&a` or `&mut a`).
1729 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1730 /// A `break`, with an optional label to break.
1731 Break(Destination, Option<&'hir Expr<'hir>>),
1732 /// A `continue`, with an optional label.
1733 Continue(Destination),
1734 /// A `return`, with an optional value to be returned.
1735 Ret(Option<&'hir Expr<'hir>>),
1736
1737 /// Inline assembly (from `asm!`), with its outputs and inputs.
1738 InlineAsm(&'hir InlineAsm<'hir>),
1739 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1740 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1741
1742 /// A struct or struct-like variant literal expression.
1743 ///
1744 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1745 /// where `base` is the `Option<Expr>`.
1746 Struct(&'hir QPath<'hir>, &'hir [ExprField<'hir>], Option<&'hir Expr<'hir>>),
1747
1748 /// An array literal constructed from one repeated element.
1749 ///
1750 /// E.g., `[1; 5]`. The first expression is the element
1751 /// to be repeated; the second is the number of times to repeat it.
1752 Repeat(&'hir Expr<'hir>, AnonConst),
1753
1754 /// A suspension point for generators (i.e., `yield <expr>`).
1755 Yield(&'hir Expr<'hir>, YieldSource),
1756
1757 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1758 Err,
1759 }
1760
1761 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1762 ///
1763 /// To resolve the path to a `DefId`, call [`qpath_res`].
1764 ///
1765 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1766 #[derive(Debug, HashStable_Generic)]
1767 pub enum QPath<'hir> {
1768 /// Path to a definition, optionally "fully-qualified" with a `Self`
1769 /// type, if the path points to an associated item in a trait.
1770 ///
1771 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1772 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1773 /// even though they both have the same two-segment `Clone::clone` `Path`.
1774 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1775
1776 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1777 /// Will be resolved by type-checking to an associated item.
1778 ///
1779 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1780 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1781 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1782 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1783
1784 /// Reference to a `#[lang = "foo"]` item.
1785 LangItem(LangItem, Span),
1786 }
1787
1788 impl<'hir> QPath<'hir> {
1789 /// Returns the span of this `QPath`.
span(&self) -> Span1790 pub fn span(&self) -> Span {
1791 match *self {
1792 QPath::Resolved(_, path) => path.span,
1793 QPath::TypeRelative(qself, ps) => qself.span.to(ps.ident.span),
1794 QPath::LangItem(_, span) => span,
1795 }
1796 }
1797
1798 /// Returns the span of the qself of this `QPath`. For example, `()` in
1799 /// `<() as Trait>::method`.
qself_span(&self) -> Span1800 pub fn qself_span(&self) -> Span {
1801 match *self {
1802 QPath::Resolved(_, path) => path.span,
1803 QPath::TypeRelative(qself, _) => qself.span,
1804 QPath::LangItem(_, span) => span,
1805 }
1806 }
1807
1808 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1809 /// `<() as Trait>::method`.
last_segment_span(&self) -> Span1810 pub fn last_segment_span(&self) -> Span {
1811 match *self {
1812 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1813 QPath::TypeRelative(_, segment) => segment.ident.span,
1814 QPath::LangItem(_, span) => span,
1815 }
1816 }
1817 }
1818
1819 /// Hints at the original code for a let statement.
1820 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1821 pub enum LocalSource {
1822 /// A `match _ { .. }`.
1823 Normal,
1824 /// When lowering async functions, we create locals within the `async move` so that
1825 /// all parameters are dropped after the future is polled.
1826 ///
1827 /// ```ignore (pseudo-Rust)
1828 /// async fn foo(<pattern> @ x: Type) {
1829 /// async move {
1830 /// let <pattern> = x;
1831 /// }
1832 /// }
1833 /// ```
1834 AsyncFn,
1835 /// A desugared `<expr>.await`.
1836 AwaitDesugar,
1837 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1838 /// The span is that of the `=` sign.
1839 AssignDesugar(Span),
1840 }
1841
1842 /// Hints at the original code for a `match _ { .. }`.
1843 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1844 #[derive(HashStable_Generic)]
1845 pub enum MatchSource {
1846 /// A `match _ { .. }`.
1847 Normal,
1848 /// A desugared `for _ in _ { .. }` loop.
1849 ForLoopDesugar,
1850 /// A desugared `?` operator.
1851 TryDesugar,
1852 /// A desugared `<expr>.await`.
1853 AwaitDesugar,
1854 }
1855
1856 impl MatchSource {
1857 #[inline]
name(self) -> &'static str1858 pub const fn name(self) -> &'static str {
1859 use MatchSource::*;
1860 match self {
1861 Normal => "match",
1862 ForLoopDesugar => "for",
1863 TryDesugar => "?",
1864 AwaitDesugar => ".await",
1865 }
1866 }
1867 }
1868
1869 /// The loop type that yielded an `ExprKind::Loop`.
1870 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1871 pub enum LoopSource {
1872 /// A `loop { .. }` loop.
1873 Loop,
1874 /// A `while _ { .. }` loop.
1875 While,
1876 /// A `for _ in _ { .. }` loop.
1877 ForLoop,
1878 }
1879
1880 impl LoopSource {
name(self) -> &'static str1881 pub fn name(self) -> &'static str {
1882 match self {
1883 LoopSource::Loop => "loop",
1884 LoopSource::While => "while",
1885 LoopSource::ForLoop => "for",
1886 }
1887 }
1888 }
1889
1890 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1891 pub enum LoopIdError {
1892 OutsideLoopScope,
1893 UnlabeledCfInWhileCondition,
1894 UnresolvedLabel,
1895 }
1896
1897 impl fmt::Display for LoopIdError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1898 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1899 f.write_str(match self {
1900 LoopIdError::OutsideLoopScope => "not inside loop scope",
1901 LoopIdError::UnlabeledCfInWhileCondition => {
1902 "unlabeled control flow (break or continue) in while condition"
1903 }
1904 LoopIdError::UnresolvedLabel => "label not found",
1905 })
1906 }
1907 }
1908
1909 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1910 pub struct Destination {
1911 // This is `Some(_)` iff there is an explicit user-specified `label
1912 pub label: Option<Label>,
1913
1914 // These errors are caught and then reported during the diagnostics pass in
1915 // librustc_passes/loops.rs
1916 pub target_id: Result<HirId, LoopIdError>,
1917 }
1918
1919 /// The yield kind that caused an `ExprKind::Yield`.
1920 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1921 pub enum YieldSource {
1922 /// An `<expr>.await`.
1923 Await { expr: Option<HirId> },
1924 /// A plain `yield`.
1925 Yield,
1926 }
1927
1928 impl YieldSource {
is_await(&self) -> bool1929 pub fn is_await(&self) -> bool {
1930 match self {
1931 YieldSource::Await { .. } => true,
1932 YieldSource::Yield => false,
1933 }
1934 }
1935 }
1936
1937 impl fmt::Display for YieldSource {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1938 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1939 f.write_str(match self {
1940 YieldSource::Await { .. } => "`await`",
1941 YieldSource::Yield => "`yield`",
1942 })
1943 }
1944 }
1945
1946 impl From<GeneratorKind> for YieldSource {
from(kind: GeneratorKind) -> Self1947 fn from(kind: GeneratorKind) -> Self {
1948 match kind {
1949 // Guess based on the kind of the current generator.
1950 GeneratorKind::Gen => Self::Yield,
1951 GeneratorKind::Async(_) => Self::Await { expr: None },
1952 }
1953 }
1954 }
1955
1956 // N.B., if you change this, you'll probably want to change the corresponding
1957 // type structure in middle/ty.rs as well.
1958 #[derive(Debug, HashStable_Generic)]
1959 pub struct MutTy<'hir> {
1960 pub ty: &'hir Ty<'hir>,
1961 pub mutbl: Mutability,
1962 }
1963
1964 /// Represents a function's signature in a trait declaration,
1965 /// trait implementation, or a free function.
1966 #[derive(Debug, HashStable_Generic)]
1967 pub struct FnSig<'hir> {
1968 pub header: FnHeader,
1969 pub decl: &'hir FnDecl<'hir>,
1970 pub span: Span,
1971 }
1972
1973 // The bodies for items are stored "out of line", in a separate
1974 // hashmap in the `Crate`. Here we just record the hir-id of the item
1975 // so it can fetched later.
1976 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1977 pub struct TraitItemId {
1978 pub def_id: LocalDefId,
1979 }
1980
1981 impl TraitItemId {
1982 #[inline]
hir_id(&self) -> HirId1983 pub fn hir_id(&self) -> HirId {
1984 // Items are always HIR owners.
1985 HirId::make_owner(self.def_id)
1986 }
1987 }
1988
1989 /// Represents an item declaration within a trait declaration,
1990 /// possibly including a default implementation. A trait item is
1991 /// either required (meaning it doesn't have an implementation, just a
1992 /// signature) or provided (meaning it has a default implementation).
1993 #[derive(Debug)]
1994 pub struct TraitItem<'hir> {
1995 pub ident: Ident,
1996 pub def_id: LocalDefId,
1997 pub generics: Generics<'hir>,
1998 pub kind: TraitItemKind<'hir>,
1999 pub span: Span,
2000 }
2001
2002 impl TraitItem<'_> {
2003 #[inline]
hir_id(&self) -> HirId2004 pub fn hir_id(&self) -> HirId {
2005 // Items are always HIR owners.
2006 HirId::make_owner(self.def_id)
2007 }
2008
trait_item_id(&self) -> TraitItemId2009 pub fn trait_item_id(&self) -> TraitItemId {
2010 TraitItemId { def_id: self.def_id }
2011 }
2012 }
2013
2014 /// Represents a trait method's body (or just argument names).
2015 #[derive(Encodable, Debug, HashStable_Generic)]
2016 pub enum TraitFn<'hir> {
2017 /// No default body in the trait, just a signature.
2018 Required(&'hir [Ident]),
2019
2020 /// Both signature and body are provided in the trait.
2021 Provided(BodyId),
2022 }
2023
2024 /// Represents a trait method or associated constant or type
2025 #[derive(Debug, HashStable_Generic)]
2026 pub enum TraitItemKind<'hir> {
2027 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
2028 Const(&'hir Ty<'hir>, Option<BodyId>),
2029 /// An associated function with an optional body.
2030 Fn(FnSig<'hir>, TraitFn<'hir>),
2031 /// An associated type with (possibly empty) bounds and optional concrete
2032 /// type.
2033 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
2034 }
2035
2036 // The bodies for items are stored "out of line", in a separate
2037 // hashmap in the `Crate`. Here we just record the hir-id of the item
2038 // so it can fetched later.
2039 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2040 pub struct ImplItemId {
2041 pub def_id: LocalDefId,
2042 }
2043
2044 impl ImplItemId {
2045 #[inline]
hir_id(&self) -> HirId2046 pub fn hir_id(&self) -> HirId {
2047 // Items are always HIR owners.
2048 HirId::make_owner(self.def_id)
2049 }
2050 }
2051
2052 /// Represents anything within an `impl` block.
2053 #[derive(Debug)]
2054 pub struct ImplItem<'hir> {
2055 pub ident: Ident,
2056 pub def_id: LocalDefId,
2057 pub vis: Visibility<'hir>,
2058 pub defaultness: Defaultness,
2059 pub generics: Generics<'hir>,
2060 pub kind: ImplItemKind<'hir>,
2061 pub span: Span,
2062 }
2063
2064 impl ImplItem<'_> {
2065 #[inline]
hir_id(&self) -> HirId2066 pub fn hir_id(&self) -> HirId {
2067 // Items are always HIR owners.
2068 HirId::make_owner(self.def_id)
2069 }
2070
impl_item_id(&self) -> ImplItemId2071 pub fn impl_item_id(&self) -> ImplItemId {
2072 ImplItemId { def_id: self.def_id }
2073 }
2074 }
2075
2076 /// Represents various kinds of content within an `impl`.
2077 #[derive(Debug, HashStable_Generic)]
2078 pub enum ImplItemKind<'hir> {
2079 /// An associated constant of the given type, set to the constant result
2080 /// of the expression.
2081 Const(&'hir Ty<'hir>, BodyId),
2082 /// An associated function implementation with the given signature and body.
2083 Fn(FnSig<'hir>, BodyId),
2084 /// An associated type.
2085 TyAlias(&'hir Ty<'hir>),
2086 }
2087
2088 // The name of the associated type for `Fn` return types.
2089 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
2090
2091 /// Bind a type to an associated type (i.e., `A = Foo`).
2092 ///
2093 /// Bindings like `A: Debug` are represented as a special type `A =
2094 /// $::Debug` that is understood by the astconv code.
2095 ///
2096 /// FIXME(alexreg): why have a separate type for the binding case,
2097 /// wouldn't it be better to make the `ty` field an enum like the
2098 /// following?
2099 ///
2100 /// ```
2101 /// enum TypeBindingKind {
2102 /// Equals(...),
2103 /// Binding(...),
2104 /// }
2105 /// ```
2106 #[derive(Debug, HashStable_Generic)]
2107 pub struct TypeBinding<'hir> {
2108 pub hir_id: HirId,
2109 #[stable_hasher(project(name))]
2110 pub ident: Ident,
2111 pub gen_args: &'hir GenericArgs<'hir>,
2112 pub kind: TypeBindingKind<'hir>,
2113 pub span: Span,
2114 }
2115
2116 // Represents the two kinds of type bindings.
2117 #[derive(Debug, HashStable_Generic)]
2118 pub enum TypeBindingKind<'hir> {
2119 /// E.g., `Foo<Bar: Send>`.
2120 Constraint { bounds: &'hir [GenericBound<'hir>] },
2121 /// E.g., `Foo<Bar = ()>`.
2122 Equality { ty: &'hir Ty<'hir> },
2123 }
2124
2125 impl TypeBinding<'_> {
ty(&self) -> &Ty<'_>2126 pub fn ty(&self) -> &Ty<'_> {
2127 match self.kind {
2128 TypeBindingKind::Equality { ref ty } => ty,
2129 _ => panic!("expected equality type binding for parenthesized generic args"),
2130 }
2131 }
2132 }
2133
2134 #[derive(Debug)]
2135 pub struct Ty<'hir> {
2136 pub hir_id: HirId,
2137 pub kind: TyKind<'hir>,
2138 pub span: Span,
2139 }
2140
2141 /// Not represented directly in the AST; referred to by name through a `ty_path`.
2142 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
2143 #[derive(HashStable_Generic)]
2144 pub enum PrimTy {
2145 Int(IntTy),
2146 Uint(UintTy),
2147 Float(FloatTy),
2148 Str,
2149 Bool,
2150 Char,
2151 }
2152
2153 impl PrimTy {
2154 /// All of the primitive types
2155 pub const ALL: [Self; 17] = [
2156 // any changes here should also be reflected in `PrimTy::from_name`
2157 Self::Int(IntTy::I8),
2158 Self::Int(IntTy::I16),
2159 Self::Int(IntTy::I32),
2160 Self::Int(IntTy::I64),
2161 Self::Int(IntTy::I128),
2162 Self::Int(IntTy::Isize),
2163 Self::Uint(UintTy::U8),
2164 Self::Uint(UintTy::U16),
2165 Self::Uint(UintTy::U32),
2166 Self::Uint(UintTy::U64),
2167 Self::Uint(UintTy::U128),
2168 Self::Uint(UintTy::Usize),
2169 Self::Float(FloatTy::F32),
2170 Self::Float(FloatTy::F64),
2171 Self::Bool,
2172 Self::Char,
2173 Self::Str,
2174 ];
2175
2176 /// Like [`PrimTy::name`], but returns a &str instead of a symbol.
2177 ///
2178 /// Used by clippy.
name_str(self) -> &'static str2179 pub fn name_str(self) -> &'static str {
2180 match self {
2181 PrimTy::Int(i) => i.name_str(),
2182 PrimTy::Uint(u) => u.name_str(),
2183 PrimTy::Float(f) => f.name_str(),
2184 PrimTy::Str => "str",
2185 PrimTy::Bool => "bool",
2186 PrimTy::Char => "char",
2187 }
2188 }
2189
name(self) -> Symbol2190 pub fn name(self) -> Symbol {
2191 match self {
2192 PrimTy::Int(i) => i.name(),
2193 PrimTy::Uint(u) => u.name(),
2194 PrimTy::Float(f) => f.name(),
2195 PrimTy::Str => sym::str,
2196 PrimTy::Bool => sym::bool,
2197 PrimTy::Char => sym::char,
2198 }
2199 }
2200
2201 /// Returns the matching `PrimTy` for a `Symbol` such as "str" or "i32".
2202 /// Returns `None` if no matching type is found.
from_name(name: Symbol) -> Option<Self>2203 pub fn from_name(name: Symbol) -> Option<Self> {
2204 let ty = match name {
2205 // any changes here should also be reflected in `PrimTy::ALL`
2206 sym::i8 => Self::Int(IntTy::I8),
2207 sym::i16 => Self::Int(IntTy::I16),
2208 sym::i32 => Self::Int(IntTy::I32),
2209 sym::i64 => Self::Int(IntTy::I64),
2210 sym::i128 => Self::Int(IntTy::I128),
2211 sym::isize => Self::Int(IntTy::Isize),
2212 sym::u8 => Self::Uint(UintTy::U8),
2213 sym::u16 => Self::Uint(UintTy::U16),
2214 sym::u32 => Self::Uint(UintTy::U32),
2215 sym::u64 => Self::Uint(UintTy::U64),
2216 sym::u128 => Self::Uint(UintTy::U128),
2217 sym::usize => Self::Uint(UintTy::Usize),
2218 sym::f32 => Self::Float(FloatTy::F32),
2219 sym::f64 => Self::Float(FloatTy::F64),
2220 sym::bool => Self::Bool,
2221 sym::char => Self::Char,
2222 sym::str => Self::Str,
2223 _ => return None,
2224 };
2225 Some(ty)
2226 }
2227 }
2228
2229 #[derive(Debug, HashStable_Generic)]
2230 pub struct BareFnTy<'hir> {
2231 pub unsafety: Unsafety,
2232 pub abi: Abi,
2233 pub generic_params: &'hir [GenericParam<'hir>],
2234 pub decl: &'hir FnDecl<'hir>,
2235 pub param_names: &'hir [Ident],
2236 }
2237
2238 #[derive(Debug, HashStable_Generic)]
2239 pub struct OpaqueTy<'hir> {
2240 pub generics: Generics<'hir>,
2241 pub bounds: GenericBounds<'hir>,
2242 pub impl_trait_fn: Option<DefId>,
2243 pub origin: OpaqueTyOrigin,
2244 }
2245
2246 /// From whence the opaque type came.
2247 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
2248 pub enum OpaqueTyOrigin {
2249 /// `-> impl Trait`
2250 FnReturn,
2251 /// `async fn`
2252 AsyncFn,
2253 /// type aliases: `type Foo = impl Trait;`
2254 TyAlias,
2255 }
2256
2257 /// The various kinds of types recognized by the compiler.
2258 #[derive(Debug, HashStable_Generic)]
2259 pub enum TyKind<'hir> {
2260 /// A variable length slice (i.e., `[T]`).
2261 Slice(&'hir Ty<'hir>),
2262 /// A fixed length array (i.e., `[T; n]`).
2263 Array(&'hir Ty<'hir>, AnonConst),
2264 /// A raw pointer (i.e., `*const T` or `*mut T`).
2265 Ptr(MutTy<'hir>),
2266 /// A reference (i.e., `&'a T` or `&'a mut T`).
2267 Rptr(Lifetime, MutTy<'hir>),
2268 /// A bare function (e.g., `fn(usize) -> bool`).
2269 BareFn(&'hir BareFnTy<'hir>),
2270 /// The never type (`!`).
2271 Never,
2272 /// A tuple (`(A, B, C, D, ...)`).
2273 Tup(&'hir [Ty<'hir>]),
2274 /// A path to a type definition (`module::module::...::Type`), or an
2275 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2276 ///
2277 /// Type parameters may be stored in each `PathSegment`.
2278 Path(QPath<'hir>),
2279 /// An opaque type definition itself. This is only used for `impl Trait`.
2280 ///
2281 /// The generic argument list contains the lifetimes (and in the future
2282 /// possibly parameters) that are actually bound on the `impl Trait`.
2283 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2284 /// A trait object type `Bound1 + Bound2 + Bound3`
2285 /// where `Bound` is a trait or a lifetime.
2286 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime, TraitObjectSyntax),
2287 /// Unused for now.
2288 Typeof(AnonConst),
2289 /// `TyKind::Infer` means the type should be inferred instead of it having been
2290 /// specified. This can appear anywhere in a type.
2291 Infer,
2292 /// Placeholder for a type that has failed to be defined.
2293 Err,
2294 }
2295
2296 #[derive(Debug, HashStable_Generic)]
2297 pub enum InlineAsmOperand<'hir> {
2298 In {
2299 reg: InlineAsmRegOrRegClass,
2300 expr: Expr<'hir>,
2301 },
2302 Out {
2303 reg: InlineAsmRegOrRegClass,
2304 late: bool,
2305 expr: Option<Expr<'hir>>,
2306 },
2307 InOut {
2308 reg: InlineAsmRegOrRegClass,
2309 late: bool,
2310 expr: Expr<'hir>,
2311 },
2312 SplitInOut {
2313 reg: InlineAsmRegOrRegClass,
2314 late: bool,
2315 in_expr: Expr<'hir>,
2316 out_expr: Option<Expr<'hir>>,
2317 },
2318 Const {
2319 anon_const: AnonConst,
2320 },
2321 Sym {
2322 expr: Expr<'hir>,
2323 },
2324 }
2325
2326 impl<'hir> InlineAsmOperand<'hir> {
reg(&self) -> Option<InlineAsmRegOrRegClass>2327 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2328 match *self {
2329 Self::In { reg, .. }
2330 | Self::Out { reg, .. }
2331 | Self::InOut { reg, .. }
2332 | Self::SplitInOut { reg, .. } => Some(reg),
2333 Self::Const { .. } | Self::Sym { .. } => None,
2334 }
2335 }
2336
is_clobber(&self) -> bool2337 pub fn is_clobber(&self) -> bool {
2338 matches!(
2339 self,
2340 InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None }
2341 )
2342 }
2343 }
2344
2345 #[derive(Debug, HashStable_Generic)]
2346 pub struct InlineAsm<'hir> {
2347 pub template: &'hir [InlineAsmTemplatePiece],
2348 pub template_strs: &'hir [(Symbol, Option<Symbol>, Span)],
2349 pub operands: &'hir [(InlineAsmOperand<'hir>, Span)],
2350 pub options: InlineAsmOptions,
2351 pub line_spans: &'hir [Span],
2352 }
2353
2354 #[derive(Copy, Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2355 pub struct LlvmInlineAsmOutput {
2356 pub constraint: Symbol,
2357 pub is_rw: bool,
2358 pub is_indirect: bool,
2359 pub span: Span,
2360 }
2361
2362 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2363 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2364 // arena-allocated slice.
2365 #[derive(Clone, Encodable, Decodable, Debug, Hash, HashStable_Generic, PartialEq)]
2366 pub struct LlvmInlineAsmInner {
2367 pub asm: Symbol,
2368 pub asm_str_style: StrStyle,
2369 pub outputs: Vec<LlvmInlineAsmOutput>,
2370 pub inputs: Vec<Symbol>,
2371 pub clobbers: Vec<Symbol>,
2372 pub volatile: bool,
2373 pub alignstack: bool,
2374 pub dialect: LlvmAsmDialect,
2375 }
2376
2377 #[derive(Debug, HashStable_Generic)]
2378 pub struct LlvmInlineAsm<'hir> {
2379 pub inner: LlvmInlineAsmInner,
2380 pub outputs_exprs: &'hir [Expr<'hir>],
2381 pub inputs_exprs: &'hir [Expr<'hir>],
2382 }
2383
2384 /// Represents a parameter in a function header.
2385 #[derive(Debug, HashStable_Generic)]
2386 pub struct Param<'hir> {
2387 pub hir_id: HirId,
2388 pub pat: &'hir Pat<'hir>,
2389 pub ty_span: Span,
2390 pub span: Span,
2391 }
2392
2393 /// Represents the header (not the body) of a function declaration.
2394 #[derive(Debug, HashStable_Generic)]
2395 pub struct FnDecl<'hir> {
2396 /// The types of the function's parameters.
2397 ///
2398 /// Additional argument data is stored in the function's [body](Body::params).
2399 pub inputs: &'hir [Ty<'hir>],
2400 pub output: FnRetTy<'hir>,
2401 pub c_variadic: bool,
2402 /// Does the function have an implicit self?
2403 pub implicit_self: ImplicitSelfKind,
2404 }
2405
2406 /// Represents what type of implicit self a function has, if any.
2407 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2408 pub enum ImplicitSelfKind {
2409 /// Represents a `fn x(self);`.
2410 Imm,
2411 /// Represents a `fn x(mut self);`.
2412 Mut,
2413 /// Represents a `fn x(&self);`.
2414 ImmRef,
2415 /// Represents a `fn x(&mut self);`.
2416 MutRef,
2417 /// Represents when a function does not have a self argument or
2418 /// when a function has a `self: X` argument.
2419 None,
2420 }
2421
2422 impl ImplicitSelfKind {
2423 /// Does this represent an implicit self?
has_implicit_self(&self) -> bool2424 pub fn has_implicit_self(&self) -> bool {
2425 !matches!(*self, ImplicitSelfKind::None)
2426 }
2427 }
2428
2429 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2430 #[derive(HashStable_Generic)]
2431 pub enum IsAsync {
2432 Async,
2433 NotAsync,
2434 }
2435
2436 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2437 pub enum Defaultness {
2438 Default { has_value: bool },
2439 Final,
2440 }
2441
2442 impl Defaultness {
has_value(&self) -> bool2443 pub fn has_value(&self) -> bool {
2444 match *self {
2445 Defaultness::Default { has_value } => has_value,
2446 Defaultness::Final => true,
2447 }
2448 }
2449
is_final(&self) -> bool2450 pub fn is_final(&self) -> bool {
2451 *self == Defaultness::Final
2452 }
2453
is_default(&self) -> bool2454 pub fn is_default(&self) -> bool {
2455 matches!(*self, Defaultness::Default { .. })
2456 }
2457 }
2458
2459 #[derive(Debug, HashStable_Generic)]
2460 pub enum FnRetTy<'hir> {
2461 /// Return type is not specified.
2462 ///
2463 /// Functions default to `()` and
2464 /// closures default to inference. Span points to where return
2465 /// type would be inserted.
2466 DefaultReturn(Span),
2467 /// Everything else.
2468 Return(&'hir Ty<'hir>),
2469 }
2470
2471 impl FnRetTy<'_> {
2472 #[inline]
span(&self) -> Span2473 pub fn span(&self) -> Span {
2474 match *self {
2475 Self::DefaultReturn(span) => span,
2476 Self::Return(ref ty) => ty.span,
2477 }
2478 }
2479 }
2480
2481 #[derive(Encodable, Debug)]
2482 pub struct Mod<'hir> {
2483 /// A span from the first token past `{` to the last token until `}`.
2484 /// For `mod foo;`, the inner span ranges from the first token
2485 /// to the last token in the external file.
2486 pub inner: Span,
2487 pub item_ids: &'hir [ItemId],
2488 }
2489
2490 #[derive(Debug, HashStable_Generic)]
2491 pub struct EnumDef<'hir> {
2492 pub variants: &'hir [Variant<'hir>],
2493 }
2494
2495 #[derive(Debug, HashStable_Generic)]
2496 pub struct Variant<'hir> {
2497 /// Name of the variant.
2498 #[stable_hasher(project(name))]
2499 pub ident: Ident,
2500 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2501 pub id: HirId,
2502 /// Fields and constructor id of the variant.
2503 pub data: VariantData<'hir>,
2504 /// Explicit discriminant (e.g., `Foo = 1`).
2505 pub disr_expr: Option<AnonConst>,
2506 /// Span
2507 pub span: Span,
2508 }
2509
2510 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2511 pub enum UseKind {
2512 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2513 /// Also produced for each element of a list `use`, e.g.
2514 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2515 Single,
2516
2517 /// Glob import, e.g., `use foo::*`.
2518 Glob,
2519
2520 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2521 /// an additional `use foo::{}` for performing checks such as
2522 /// unstable feature gating. May be removed in the future.
2523 ListStem,
2524 }
2525
2526 /// References to traits in impls.
2527 ///
2528 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2529 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2530 /// trait being referred to but just a unique `HirId` that serves as a key
2531 /// within the resolution map.
2532 #[derive(Clone, Debug, HashStable_Generic)]
2533 pub struct TraitRef<'hir> {
2534 pub path: &'hir Path<'hir>,
2535 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2536 #[stable_hasher(ignore)]
2537 pub hir_ref_id: HirId,
2538 }
2539
2540 impl TraitRef<'_> {
2541 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
trait_def_id(&self) -> Option<DefId>2542 pub fn trait_def_id(&self) -> Option<DefId> {
2543 match self.path.res {
2544 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2545 Res::Err => None,
2546 _ => unreachable!(),
2547 }
2548 }
2549 }
2550
2551 #[derive(Clone, Debug, HashStable_Generic)]
2552 pub struct PolyTraitRef<'hir> {
2553 /// The `'a` in `for<'a> Foo<&'a T>`.
2554 pub bound_generic_params: &'hir [GenericParam<'hir>],
2555
2556 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2557 pub trait_ref: TraitRef<'hir>,
2558
2559 pub span: Span,
2560 }
2561
2562 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2563
2564 #[derive(Copy, Clone, Debug)]
2565 pub enum VisibilityKind<'hir> {
2566 Public,
2567 Crate(CrateSugar),
2568 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2569 Inherited,
2570 }
2571
2572 impl VisibilityKind<'_> {
is_pub(&self) -> bool2573 pub fn is_pub(&self) -> bool {
2574 matches!(*self, VisibilityKind::Public)
2575 }
2576
is_pub_restricted(&self) -> bool2577 pub fn is_pub_restricted(&self) -> bool {
2578 match *self {
2579 VisibilityKind::Public | VisibilityKind::Inherited => false,
2580 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2581 }
2582 }
2583 }
2584
2585 #[derive(Debug, HashStable_Generic)]
2586 pub struct FieldDef<'hir> {
2587 pub span: Span,
2588 #[stable_hasher(project(name))]
2589 pub ident: Ident,
2590 pub vis: Visibility<'hir>,
2591 pub hir_id: HirId,
2592 pub ty: &'hir Ty<'hir>,
2593 }
2594
2595 impl FieldDef<'_> {
2596 // Still necessary in couple of places
is_positional(&self) -> bool2597 pub fn is_positional(&self) -> bool {
2598 let first = self.ident.as_str().as_bytes()[0];
2599 (b'0'..=b'9').contains(&first)
2600 }
2601 }
2602
2603 /// Fields and constructor IDs of enum variants and structs.
2604 #[derive(Debug, HashStable_Generic)]
2605 pub enum VariantData<'hir> {
2606 /// A struct variant.
2607 ///
2608 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2609 Struct(&'hir [FieldDef<'hir>], /* recovered */ bool),
2610 /// A tuple variant.
2611 ///
2612 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2613 Tuple(&'hir [FieldDef<'hir>], HirId),
2614 /// A unit variant.
2615 ///
2616 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2617 Unit(HirId),
2618 }
2619
2620 impl VariantData<'hir> {
2621 /// Return the fields of this variant.
fields(&self) -> &'hir [FieldDef<'hir>]2622 pub fn fields(&self) -> &'hir [FieldDef<'hir>] {
2623 match *self {
2624 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2625 _ => &[],
2626 }
2627 }
2628
2629 /// Return the `HirId` of this variant's constructor, if it has one.
ctor_hir_id(&self) -> Option<HirId>2630 pub fn ctor_hir_id(&self) -> Option<HirId> {
2631 match *self {
2632 VariantData::Struct(_, _) => None,
2633 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2634 }
2635 }
2636 }
2637
2638 // The bodies for items are stored "out of line", in a separate
2639 // hashmap in the `Crate`. Here we just record the hir-id of the item
2640 // so it can fetched later.
2641 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug, Hash)]
2642 pub struct ItemId {
2643 pub def_id: LocalDefId,
2644 }
2645
2646 impl ItemId {
2647 #[inline]
hir_id(&self) -> HirId2648 pub fn hir_id(&self) -> HirId {
2649 // Items are always HIR owners.
2650 HirId::make_owner(self.def_id)
2651 }
2652 }
2653
2654 /// An item
2655 ///
2656 /// The name might be a dummy name in case of anonymous items
2657 #[derive(Debug)]
2658 pub struct Item<'hir> {
2659 pub ident: Ident,
2660 pub def_id: LocalDefId,
2661 pub kind: ItemKind<'hir>,
2662 pub vis: Visibility<'hir>,
2663 pub span: Span,
2664 }
2665
2666 impl Item<'_> {
2667 #[inline]
hir_id(&self) -> HirId2668 pub fn hir_id(&self) -> HirId {
2669 // Items are always HIR owners.
2670 HirId::make_owner(self.def_id)
2671 }
2672
item_id(&self) -> ItemId2673 pub fn item_id(&self) -> ItemId {
2674 ItemId { def_id: self.def_id }
2675 }
2676 }
2677
2678 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2679 #[derive(Encodable, Decodable, HashStable_Generic)]
2680 pub enum Unsafety {
2681 Unsafe,
2682 Normal,
2683 }
2684
2685 impl Unsafety {
prefix_str(&self) -> &'static str2686 pub fn prefix_str(&self) -> &'static str {
2687 match self {
2688 Self::Unsafe => "unsafe ",
2689 Self::Normal => "",
2690 }
2691 }
2692 }
2693
2694 impl fmt::Display for Unsafety {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result2695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2696 f.write_str(match *self {
2697 Self::Unsafe => "unsafe",
2698 Self::Normal => "normal",
2699 })
2700 }
2701 }
2702
2703 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2704 #[derive(Encodable, Decodable, HashStable_Generic)]
2705 pub enum Constness {
2706 Const,
2707 NotConst,
2708 }
2709
2710 impl fmt::Display for Constness {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result2711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2712 f.write_str(match *self {
2713 Self::Const => "const",
2714 Self::NotConst => "non-const",
2715 })
2716 }
2717 }
2718
2719 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2720 pub struct FnHeader {
2721 pub unsafety: Unsafety,
2722 pub constness: Constness,
2723 pub asyncness: IsAsync,
2724 pub abi: Abi,
2725 }
2726
2727 impl FnHeader {
is_const(&self) -> bool2728 pub fn is_const(&self) -> bool {
2729 matches!(&self.constness, Constness::Const)
2730 }
2731 }
2732
2733 #[derive(Debug, HashStable_Generic)]
2734 pub enum ItemKind<'hir> {
2735 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2736 ///
2737 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2738 ExternCrate(Option<Symbol>),
2739
2740 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2741 ///
2742 /// or just
2743 ///
2744 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2745 Use(&'hir Path<'hir>, UseKind),
2746
2747 /// A `static` item.
2748 Static(&'hir Ty<'hir>, Mutability, BodyId),
2749 /// A `const` item.
2750 Const(&'hir Ty<'hir>, BodyId),
2751 /// A function declaration.
2752 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2753 /// A MBE macro definition (`macro_rules!` or `macro`).
2754 Macro(ast::MacroDef),
2755 /// A module.
2756 Mod(Mod<'hir>),
2757 /// An external module, e.g. `extern { .. }`.
2758 ForeignMod { abi: Abi, items: &'hir [ForeignItemRef] },
2759 /// Module-level inline assembly (from `global_asm!`).
2760 GlobalAsm(&'hir InlineAsm<'hir>),
2761 /// A type alias, e.g., `type Foo = Bar<u8>`.
2762 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2763 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2764 OpaqueTy(OpaqueTy<'hir>),
2765 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2766 Enum(EnumDef<'hir>, Generics<'hir>),
2767 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2768 Struct(VariantData<'hir>, Generics<'hir>),
2769 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2770 Union(VariantData<'hir>, Generics<'hir>),
2771 /// A trait definition.
2772 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2773 /// A trait alias.
2774 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2775
2776 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2777 Impl(Impl<'hir>),
2778 }
2779
2780 #[derive(Debug, HashStable_Generic)]
2781 pub struct Impl<'hir> {
2782 pub unsafety: Unsafety,
2783 pub polarity: ImplPolarity,
2784 pub defaultness: Defaultness,
2785 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2786 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2787 pub defaultness_span: Option<Span>,
2788 pub constness: Constness,
2789 pub generics: Generics<'hir>,
2790
2791 /// The trait being implemented, if any.
2792 pub of_trait: Option<TraitRef<'hir>>,
2793
2794 pub self_ty: &'hir Ty<'hir>,
2795 pub items: &'hir [ImplItemRef],
2796 }
2797
2798 impl ItemKind<'_> {
generics(&self) -> Option<&Generics<'_>>2799 pub fn generics(&self) -> Option<&Generics<'_>> {
2800 Some(match *self {
2801 ItemKind::Fn(_, ref generics, _)
2802 | ItemKind::TyAlias(_, ref generics)
2803 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2804 | ItemKind::Enum(_, ref generics)
2805 | ItemKind::Struct(_, ref generics)
2806 | ItemKind::Union(_, ref generics)
2807 | ItemKind::Trait(_, _, ref generics, _, _)
2808 | ItemKind::Impl(Impl { ref generics, .. }) => generics,
2809 _ => return None,
2810 })
2811 }
2812
descr(&self) -> &'static str2813 pub fn descr(&self) -> &'static str {
2814 match self {
2815 ItemKind::ExternCrate(..) => "extern crate",
2816 ItemKind::Use(..) => "`use` import",
2817 ItemKind::Static(..) => "static item",
2818 ItemKind::Const(..) => "constant item",
2819 ItemKind::Fn(..) => "function",
2820 ItemKind::Macro(..) => "macro",
2821 ItemKind::Mod(..) => "module",
2822 ItemKind::ForeignMod { .. } => "extern block",
2823 ItemKind::GlobalAsm(..) => "global asm item",
2824 ItemKind::TyAlias(..) => "type alias",
2825 ItemKind::OpaqueTy(..) => "opaque type",
2826 ItemKind::Enum(..) => "enum",
2827 ItemKind::Struct(..) => "struct",
2828 ItemKind::Union(..) => "union",
2829 ItemKind::Trait(..) => "trait",
2830 ItemKind::TraitAlias(..) => "trait alias",
2831 ItemKind::Impl(..) => "implementation",
2832 }
2833 }
2834 }
2835
2836 /// A reference from an trait to one of its associated items. This
2837 /// contains the item's id, naturally, but also the item's name and
2838 /// some other high-level details (like whether it is an associated
2839 /// type or method, and whether it is public). This allows other
2840 /// passes to find the impl they want without loading the ID (which
2841 /// means fewer edges in the incremental compilation graph).
2842 #[derive(Encodable, Debug, HashStable_Generic)]
2843 pub struct TraitItemRef {
2844 pub id: TraitItemId,
2845 #[stable_hasher(project(name))]
2846 pub ident: Ident,
2847 pub kind: AssocItemKind,
2848 pub span: Span,
2849 pub defaultness: Defaultness,
2850 }
2851
2852 /// A reference from an impl to one of its associated items. This
2853 /// contains the item's ID, naturally, but also the item's name and
2854 /// some other high-level details (like whether it is an associated
2855 /// type or method, and whether it is public). This allows other
2856 /// passes to find the impl they want without loading the ID (which
2857 /// means fewer edges in the incremental compilation graph).
2858 #[derive(Debug, HashStable_Generic)]
2859 pub struct ImplItemRef {
2860 pub id: ImplItemId,
2861 #[stable_hasher(project(name))]
2862 pub ident: Ident,
2863 pub kind: AssocItemKind,
2864 pub span: Span,
2865 pub defaultness: Defaultness,
2866 }
2867
2868 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2869 pub enum AssocItemKind {
2870 Const,
2871 Fn { has_self: bool },
2872 Type,
2873 }
2874
2875 // The bodies for items are stored "out of line", in a separate
2876 // hashmap in the `Crate`. Here we just record the hir-id of the item
2877 // so it can fetched later.
2878 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
2879 pub struct ForeignItemId {
2880 pub def_id: LocalDefId,
2881 }
2882
2883 impl ForeignItemId {
2884 #[inline]
hir_id(&self) -> HirId2885 pub fn hir_id(&self) -> HirId {
2886 // Items are always HIR owners.
2887 HirId::make_owner(self.def_id)
2888 }
2889 }
2890
2891 /// A reference from a foreign block to one of its items. This
2892 /// contains the item's ID, naturally, but also the item's name and
2893 /// some other high-level details (like whether it is an associated
2894 /// type or method, and whether it is public). This allows other
2895 /// passes to find the impl they want without loading the ID (which
2896 /// means fewer edges in the incremental compilation graph).
2897 #[derive(Debug, HashStable_Generic)]
2898 pub struct ForeignItemRef {
2899 pub id: ForeignItemId,
2900 #[stable_hasher(project(name))]
2901 pub ident: Ident,
2902 pub span: Span,
2903 }
2904
2905 #[derive(Debug)]
2906 pub struct ForeignItem<'hir> {
2907 pub ident: Ident,
2908 pub kind: ForeignItemKind<'hir>,
2909 pub def_id: LocalDefId,
2910 pub span: Span,
2911 pub vis: Visibility<'hir>,
2912 }
2913
2914 impl ForeignItem<'_> {
2915 #[inline]
hir_id(&self) -> HirId2916 pub fn hir_id(&self) -> HirId {
2917 // Items are always HIR owners.
2918 HirId::make_owner(self.def_id)
2919 }
2920
foreign_item_id(&self) -> ForeignItemId2921 pub fn foreign_item_id(&self) -> ForeignItemId {
2922 ForeignItemId { def_id: self.def_id }
2923 }
2924 }
2925
2926 /// An item within an `extern` block.
2927 #[derive(Debug, HashStable_Generic)]
2928 pub enum ForeignItemKind<'hir> {
2929 /// A foreign function.
2930 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2931 /// A foreign static item (`static ext: u8`).
2932 Static(&'hir Ty<'hir>, Mutability),
2933 /// A foreign type.
2934 Type,
2935 }
2936
2937 /// A variable captured by a closure.
2938 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2939 pub struct Upvar {
2940 // First span where it is accessed (there can be multiple).
2941 pub span: Span,
2942 }
2943
2944 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2945 // has length > 0 if the trait is found through an chain of imports, starting with the
2946 // import/use statement in the scope where the trait is used.
2947 #[derive(Encodable, Decodable, Clone, Debug)]
2948 pub struct TraitCandidate {
2949 pub def_id: DefId,
2950 pub import_ids: SmallVec<[LocalDefId; 1]>,
2951 }
2952
2953 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2954 pub enum OwnerNode<'hir> {
2955 Item(&'hir Item<'hir>),
2956 ForeignItem(&'hir ForeignItem<'hir>),
2957 TraitItem(&'hir TraitItem<'hir>),
2958 ImplItem(&'hir ImplItem<'hir>),
2959 Crate(&'hir Mod<'hir>),
2960 }
2961
2962 impl<'hir> OwnerNode<'hir> {
ident(&self) -> Option<Ident>2963 pub fn ident(&self) -> Option<Ident> {
2964 match self {
2965 OwnerNode::Item(Item { ident, .. })
2966 | OwnerNode::ForeignItem(ForeignItem { ident, .. })
2967 | OwnerNode::ImplItem(ImplItem { ident, .. })
2968 | OwnerNode::TraitItem(TraitItem { ident, .. }) => Some(*ident),
2969 OwnerNode::Crate(..) => None,
2970 }
2971 }
2972
span(&self) -> Span2973 pub fn span(&self) -> Span {
2974 match self {
2975 OwnerNode::Item(Item { span, .. })
2976 | OwnerNode::ForeignItem(ForeignItem { span, .. })
2977 | OwnerNode::ImplItem(ImplItem { span, .. })
2978 | OwnerNode::TraitItem(TraitItem { span, .. })
2979 | OwnerNode::Crate(Mod { inner: span, .. }) => *span,
2980 }
2981 }
2982
fn_decl(&self) -> Option<&FnDecl<'hir>>2983 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2984 match self {
2985 OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2986 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2987 | OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2988 OwnerNode::ForeignItem(ForeignItem {
2989 kind: ForeignItemKind::Fn(fn_decl, _, _),
2990 ..
2991 }) => Some(fn_decl),
2992 _ => None,
2993 }
2994 }
2995
body_id(&self) -> Option<BodyId>2996 pub fn body_id(&self) -> Option<BodyId> {
2997 match self {
2998 OwnerNode::TraitItem(TraitItem {
2999 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3000 ..
3001 })
3002 | OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3003 | OwnerNode::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3004 _ => None,
3005 }
3006 }
3007
generics(&self) -> Option<&'hir Generics<'hir>>3008 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3009 match self {
3010 OwnerNode::TraitItem(TraitItem { generics, .. })
3011 | OwnerNode::ImplItem(ImplItem { generics, .. }) => Some(generics),
3012 OwnerNode::Item(item) => item.kind.generics(),
3013 _ => None,
3014 }
3015 }
3016
def_id(self) -> LocalDefId3017 pub fn def_id(self) -> LocalDefId {
3018 match self {
3019 OwnerNode::Item(Item { def_id, .. })
3020 | OwnerNode::TraitItem(TraitItem { def_id, .. })
3021 | OwnerNode::ImplItem(ImplItem { def_id, .. })
3022 | OwnerNode::ForeignItem(ForeignItem { def_id, .. }) => *def_id,
3023 OwnerNode::Crate(..) => crate::CRATE_HIR_ID.owner,
3024 }
3025 }
3026
expect_item(self) -> &'hir Item<'hir>3027 pub fn expect_item(self) -> &'hir Item<'hir> {
3028 match self {
3029 OwnerNode::Item(n) => n,
3030 _ => panic!(),
3031 }
3032 }
3033
expect_foreign_item(self) -> &'hir ForeignItem<'hir>3034 pub fn expect_foreign_item(self) -> &'hir ForeignItem<'hir> {
3035 match self {
3036 OwnerNode::ForeignItem(n) => n,
3037 _ => panic!(),
3038 }
3039 }
3040
expect_impl_item(self) -> &'hir ImplItem<'hir>3041 pub fn expect_impl_item(self) -> &'hir ImplItem<'hir> {
3042 match self {
3043 OwnerNode::ImplItem(n) => n,
3044 _ => panic!(),
3045 }
3046 }
3047
expect_trait_item(self) -> &'hir TraitItem<'hir>3048 pub fn expect_trait_item(self) -> &'hir TraitItem<'hir> {
3049 match self {
3050 OwnerNode::TraitItem(n) => n,
3051 _ => panic!(),
3052 }
3053 }
3054 }
3055
3056 impl<'hir> Into<OwnerNode<'hir>> for &'hir Item<'hir> {
into(self) -> OwnerNode<'hir>3057 fn into(self) -> OwnerNode<'hir> {
3058 OwnerNode::Item(self)
3059 }
3060 }
3061
3062 impl<'hir> Into<OwnerNode<'hir>> for &'hir ForeignItem<'hir> {
into(self) -> OwnerNode<'hir>3063 fn into(self) -> OwnerNode<'hir> {
3064 OwnerNode::ForeignItem(self)
3065 }
3066 }
3067
3068 impl<'hir> Into<OwnerNode<'hir>> for &'hir ImplItem<'hir> {
into(self) -> OwnerNode<'hir>3069 fn into(self) -> OwnerNode<'hir> {
3070 OwnerNode::ImplItem(self)
3071 }
3072 }
3073
3074 impl<'hir> Into<OwnerNode<'hir>> for &'hir TraitItem<'hir> {
into(self) -> OwnerNode<'hir>3075 fn into(self) -> OwnerNode<'hir> {
3076 OwnerNode::TraitItem(self)
3077 }
3078 }
3079
3080 impl<'hir> Into<Node<'hir>> for OwnerNode<'hir> {
into(self) -> Node<'hir>3081 fn into(self) -> Node<'hir> {
3082 match self {
3083 OwnerNode::Item(n) => Node::Item(n),
3084 OwnerNode::ForeignItem(n) => Node::ForeignItem(n),
3085 OwnerNode::ImplItem(n) => Node::ImplItem(n),
3086 OwnerNode::TraitItem(n) => Node::TraitItem(n),
3087 OwnerNode::Crate(n) => Node::Crate(n),
3088 }
3089 }
3090 }
3091
3092 #[derive(Copy, Clone, Debug, HashStable_Generic)]
3093 pub enum Node<'hir> {
3094 Param(&'hir Param<'hir>),
3095 Item(&'hir Item<'hir>),
3096 ForeignItem(&'hir ForeignItem<'hir>),
3097 TraitItem(&'hir TraitItem<'hir>),
3098 ImplItem(&'hir ImplItem<'hir>),
3099 Variant(&'hir Variant<'hir>),
3100 Field(&'hir FieldDef<'hir>),
3101 AnonConst(&'hir AnonConst),
3102 Expr(&'hir Expr<'hir>),
3103 Stmt(&'hir Stmt<'hir>),
3104 PathSegment(&'hir PathSegment<'hir>),
3105 Ty(&'hir Ty<'hir>),
3106 TraitRef(&'hir TraitRef<'hir>),
3107 Binding(&'hir Pat<'hir>),
3108 Pat(&'hir Pat<'hir>),
3109 Arm(&'hir Arm<'hir>),
3110 Block(&'hir Block<'hir>),
3111 Local(&'hir Local<'hir>),
3112
3113 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
3114 /// with synthesized constructors.
3115 Ctor(&'hir VariantData<'hir>),
3116
3117 Lifetime(&'hir Lifetime),
3118 GenericParam(&'hir GenericParam<'hir>),
3119 Visibility(&'hir Visibility<'hir>),
3120
3121 Crate(&'hir Mod<'hir>),
3122
3123 Infer(&'hir InferArg),
3124 }
3125
3126 impl<'hir> Node<'hir> {
3127 /// Get the identifier of this `Node`, if applicable.
3128 ///
3129 /// # Edge cases
3130 ///
3131 /// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3132 /// because `Ctor`s do not have identifiers themselves.
3133 /// Instead, call `.ident()` on the parent struct/variant, like so:
3134 ///
3135 /// ```ignore (illustrative)
3136 /// ctor
3137 /// .ctor_hir_id()
3138 /// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3139 /// .and_then(|parent| parent.ident())
3140 /// ```
ident(&self) -> Option<Ident>3141 pub fn ident(&self) -> Option<Ident> {
3142 match self {
3143 Node::TraitItem(TraitItem { ident, .. })
3144 | Node::ImplItem(ImplItem { ident, .. })
3145 | Node::ForeignItem(ForeignItem { ident, .. })
3146 | Node::Field(FieldDef { ident, .. })
3147 | Node::Variant(Variant { ident, .. })
3148 | Node::Item(Item { ident, .. })
3149 | Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3150 Node::Lifetime(lt) => Some(lt.name.ident()),
3151 Node::GenericParam(p) => Some(p.name.ident()),
3152 Node::Param(..)
3153 | Node::AnonConst(..)
3154 | Node::Expr(..)
3155 | Node::Stmt(..)
3156 | Node::Block(..)
3157 | Node::Ctor(..)
3158 | Node::Pat(..)
3159 | Node::Binding(..)
3160 | Node::Arm(..)
3161 | Node::Local(..)
3162 | Node::Visibility(..)
3163 | Node::Crate(..)
3164 | Node::Ty(..)
3165 | Node::TraitRef(..)
3166 | Node::Infer(..) => None,
3167 }
3168 }
3169
fn_decl(&self) -> Option<&FnDecl<'hir>>3170 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
3171 match self {
3172 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3173 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3174 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
3175 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
3176 Some(fn_decl)
3177 }
3178 _ => None,
3179 }
3180 }
3181
body_id(&self) -> Option<BodyId>3182 pub fn body_id(&self) -> Option<BodyId> {
3183 match self {
3184 Node::TraitItem(TraitItem {
3185 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
3186 ..
3187 })
3188 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
3189 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
3190 _ => None,
3191 }
3192 }
3193
generics(&self) -> Option<&'hir Generics<'hir>>3194 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
3195 match self {
3196 Node::TraitItem(TraitItem { generics, .. })
3197 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
3198 Node::Item(item) => item.kind.generics(),
3199 _ => None,
3200 }
3201 }
3202
hir_id(&self) -> Option<HirId>3203 pub fn hir_id(&self) -> Option<HirId> {
3204 match self {
3205 Node::Item(Item { def_id, .. })
3206 | Node::TraitItem(TraitItem { def_id, .. })
3207 | Node::ImplItem(ImplItem { def_id, .. })
3208 | Node::ForeignItem(ForeignItem { def_id, .. }) => Some(HirId::make_owner(*def_id)),
3209 Node::Field(FieldDef { hir_id, .. })
3210 | Node::AnonConst(AnonConst { hir_id, .. })
3211 | Node::Expr(Expr { hir_id, .. })
3212 | Node::Stmt(Stmt { hir_id, .. })
3213 | Node::Ty(Ty { hir_id, .. })
3214 | Node::Binding(Pat { hir_id, .. })
3215 | Node::Pat(Pat { hir_id, .. })
3216 | Node::Arm(Arm { hir_id, .. })
3217 | Node::Block(Block { hir_id, .. })
3218 | Node::Local(Local { hir_id, .. })
3219 | Node::Lifetime(Lifetime { hir_id, .. })
3220 | Node::Param(Param { hir_id, .. })
3221 | Node::Infer(InferArg { hir_id, .. })
3222 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
3223 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
3224 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
3225 Node::Variant(Variant { id, .. }) => Some(*id),
3226 Node::Ctor(variant) => variant.ctor_hir_id(),
3227 Node::Crate(_) | Node::Visibility(_) => None,
3228 }
3229 }
3230
3231 /// Returns `Constness::Const` when this node is a const fn/impl/item.
constness_for_typeck(&self) -> Constness3232 pub fn constness_for_typeck(&self) -> Constness {
3233 match self {
3234 Node::Item(Item {
3235 kind: ItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3236 ..
3237 })
3238 | Node::TraitItem(TraitItem {
3239 kind: TraitItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3240 ..
3241 })
3242 | Node::ImplItem(ImplItem {
3243 kind: ImplItemKind::Fn(FnSig { header: FnHeader { constness, .. }, .. }, ..),
3244 ..
3245 })
3246 | Node::Item(Item { kind: ItemKind::Impl(Impl { constness, .. }), .. }) => *constness,
3247
3248 Node::Item(Item { kind: ItemKind::Const(..), .. })
3249 | Node::TraitItem(TraitItem { kind: TraitItemKind::Const(..), .. })
3250 | Node::ImplItem(ImplItem { kind: ImplItemKind::Const(..), .. }) => Constness::Const,
3251
3252 _ => Constness::NotConst,
3253 }
3254 }
3255
as_owner(self) -> Option<OwnerNode<'hir>>3256 pub fn as_owner(self) -> Option<OwnerNode<'hir>> {
3257 match self {
3258 Node::Item(i) => Some(OwnerNode::Item(i)),
3259 Node::ForeignItem(i) => Some(OwnerNode::ForeignItem(i)),
3260 Node::TraitItem(i) => Some(OwnerNode::TraitItem(i)),
3261 Node::ImplItem(i) => Some(OwnerNode::ImplItem(i)),
3262 Node::Crate(i) => Some(OwnerNode::Crate(i)),
3263 _ => None,
3264 }
3265 }
3266
fn_kind(self) -> Option<FnKind<'hir>>3267 pub fn fn_kind(self) -> Option<FnKind<'hir>> {
3268 match self {
3269 Node::Item(i) => match i.kind {
3270 ItemKind::Fn(ref sig, ref generics, _) => {
3271 Some(FnKind::ItemFn(i.ident, generics, sig.header, &i.vis))
3272 }
3273 _ => None,
3274 },
3275 Node::TraitItem(ti) => match ti.kind {
3276 TraitItemKind::Fn(ref sig, TraitFn::Provided(_)) => {
3277 Some(FnKind::Method(ti.ident, sig, None))
3278 }
3279 _ => None,
3280 },
3281 Node::ImplItem(ii) => match ii.kind {
3282 ImplItemKind::Fn(ref sig, _) => Some(FnKind::Method(ii.ident, sig, Some(&ii.vis))),
3283 _ => None,
3284 },
3285 Node::Expr(e) => match e.kind {
3286 ExprKind::Closure(..) => Some(FnKind::Closure),
3287 _ => None,
3288 },
3289 _ => None,
3290 }
3291 }
3292 }
3293
3294 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3295 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3296 mod size_asserts {
3297 rustc_data_structures::static_assert_size!(super::Block<'static>, 48);
3298 rustc_data_structures::static_assert_size!(super::Expr<'static>, 64);
3299 rustc_data_structures::static_assert_size!(super::Pat<'static>, 88);
3300 rustc_data_structures::static_assert_size!(super::QPath<'static>, 24);
3301 rustc_data_structures::static_assert_size!(super::Ty<'static>, 72);
3302
3303 rustc_data_structures::static_assert_size!(super::Item<'static>, 184);
3304 rustc_data_structures::static_assert_size!(super::TraitItem<'static>, 128);
3305 rustc_data_structures::static_assert_size!(super::ImplItem<'static>, 152);
3306 rustc_data_structures::static_assert_size!(super::ForeignItem<'static>, 136);
3307 }
3308