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