]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_hir/src/hir.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.git] / compiler / rustc_hir / src / hir.rs
1 use crate::def::{DefKind, Namespace, Res};
2 use crate::def_id::DefId;
3 crate use crate::hir_id::HirId;
4 use crate::{itemlikevisit, LangItem};
5
6 use rustc_ast::util::parser::ExprPrecedence;
7 use rustc_ast::{self as ast, CrateSugar, LlvmAsmDialect};
8 use rustc_ast::{AttrVec, Attribute, FloatTy, IntTy, Label, LitKind, StrStyle, UintTy};
9 pub use rustc_ast::{BorrowKind, ImplPolarity, IsAuto};
10 pub use rustc_ast::{CaptureBy, Movability, Mutability};
11 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
12 use rustc_data_structures::sync::{par_for_each_in, Send, Sync};
13 use rustc_macros::HashStable_Generic;
14 use rustc_span::def_id::LocalDefId;
15 use rustc_span::source_map::Spanned;
16 use rustc_span::symbol::{kw, sym, Ident, Symbol};
17 use rustc_span::{MultiSpan, Span, DUMMY_SP};
18 use rustc_target::asm::InlineAsmRegOrRegClass;
19 use rustc_target::spec::abi::Abi;
20
21 use smallvec::SmallVec;
22 use std::collections::{BTreeMap, BTreeSet};
23 use std::fmt;
24
25 #[derive(Copy, Clone, Encodable, HashStable_Generic)]
26 pub struct Lifetime {
27 pub hir_id: HirId,
28 pub span: Span,
29
30 /// Either "`'a`", referring to a named lifetime definition,
31 /// or "``" (i.e., `kw::Invalid`), for elision placeholders.
32 ///
33 /// HIR lowering inserts these placeholders in type paths that
34 /// refer to type definitions needing lifetime parameters,
35 /// `&T` and `&mut T`, and trait objects without `... + 'a`.
36 pub name: LifetimeName,
37 }
38
39 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
40 #[derive(HashStable_Generic)]
41 pub enum ParamName {
42 /// Some user-given name like `T` or `'x`.
43 Plain(Ident),
44
45 /// Synthetic name generated when user elided a lifetime in an impl header.
46 ///
47 /// E.g., the lifetimes in cases like these:
48 ///
49 /// impl Foo for &u32
50 /// impl Foo<'_> for u32
51 ///
52 /// in that case, we rewrite to
53 ///
54 /// impl<'f> Foo for &'f u32
55 /// impl<'f> Foo<'f> for u32
56 ///
57 /// where `'f` is something like `Fresh(0)`. The indices are
58 /// unique per impl, but not necessarily continuous.
59 Fresh(usize),
60
61 /// Indicates an illegal name was given and an error has been
62 /// reported (so we should squelch other derived errors). Occurs
63 /// when, e.g., `'_` is used in the wrong place.
64 Error,
65 }
66
67 impl ParamName {
68 pub fn ident(&self) -> Ident {
69 match *self {
70 ParamName::Plain(ident) => ident,
71 ParamName::Fresh(_) | ParamName::Error => {
72 Ident::with_dummy_span(kw::UnderscoreLifetime)
73 }
74 }
75 }
76
77 pub fn normalize_to_macros_2_0(&self) -> ParamName {
78 match *self {
79 ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()),
80 param_name => param_name,
81 }
82 }
83 }
84
85 #[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)]
86 #[derive(HashStable_Generic)]
87 pub enum LifetimeName {
88 /// User-given names or fresh (synthetic) names.
89 Param(ParamName),
90
91 /// User wrote nothing (e.g., the lifetime in `&u32`).
92 Implicit,
93
94 /// Implicit lifetime in a context like `dyn Foo`. This is
95 /// distinguished from implicit lifetimes elsewhere because the
96 /// lifetime that they default to must appear elsewhere within the
97 /// enclosing type. This means that, in an `impl Trait` context, we
98 /// don't have to create a parameter for them. That is, `impl
99 /// Trait<Item = &u32>` expands to an opaque type like `type
100 /// Foo<'a> = impl Trait<Item = &'a u32>`, but `impl Trait<item =
101 /// dyn Bar>` expands to `type Foo = impl Trait<Item = dyn Bar +
102 /// 'static>`. The latter uses `ImplicitObjectLifetimeDefault` so
103 /// that surrounding code knows not to create a lifetime
104 /// parameter.
105 ImplicitObjectLifetimeDefault,
106
107 /// Indicates an error during lowering (usually `'_` in wrong place)
108 /// that was already reported.
109 Error,
110
111 /// User wrote specifies `'_`.
112 Underscore,
113
114 /// User wrote `'static`.
115 Static,
116 }
117
118 impl LifetimeName {
119 pub fn ident(&self) -> Ident {
120 match *self {
121 LifetimeName::ImplicitObjectLifetimeDefault
122 | LifetimeName::Implicit
123 | LifetimeName::Error => Ident::invalid(),
124 LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
125 LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
126 LifetimeName::Param(param_name) => param_name.ident(),
127 }
128 }
129
130 pub fn is_elided(&self) -> bool {
131 match self {
132 LifetimeName::ImplicitObjectLifetimeDefault
133 | LifetimeName::Implicit
134 | LifetimeName::Underscore => true,
135
136 // It might seem surprising that `Fresh(_)` counts as
137 // *not* elided -- but this is because, as far as the code
138 // in the compiler is concerned -- `Fresh(_)` variants act
139 // equivalently to "some fresh name". They correspond to
140 // early-bound regions on an impl, in other words.
141 LifetimeName::Error | LifetimeName::Param(_) | LifetimeName::Static => false,
142 }
143 }
144
145 fn is_static(&self) -> bool {
146 self == &LifetimeName::Static
147 }
148
149 pub fn normalize_to_macros_2_0(&self) -> LifetimeName {
150 match *self {
151 LifetimeName::Param(param_name) => {
152 LifetimeName::Param(param_name.normalize_to_macros_2_0())
153 }
154 lifetime_name => lifetime_name,
155 }
156 }
157 }
158
159 impl fmt::Display for Lifetime {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 self.name.ident().fmt(f)
162 }
163 }
164
165 impl fmt::Debug for Lifetime {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 write!(f, "lifetime({}: {})", self.hir_id, self.name.ident())
168 }
169 }
170
171 impl Lifetime {
172 pub fn is_elided(&self) -> bool {
173 self.name.is_elided()
174 }
175
176 pub fn is_static(&self) -> bool {
177 self.name.is_static()
178 }
179 }
180
181 /// A `Path` is essentially Rust's notion of a name; for instance,
182 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
183 /// along with a bunch of supporting information.
184 #[derive(Debug, HashStable_Generic)]
185 pub struct Path<'hir> {
186 pub span: Span,
187 /// The resolution for the path.
188 pub res: Res,
189 /// The segments in the path: the things separated by `::`.
190 pub segments: &'hir [PathSegment<'hir>],
191 }
192
193 impl Path<'_> {
194 pub fn is_global(&self) -> bool {
195 !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
196 }
197 }
198
199 /// A segment of a path: an identifier, an optional lifetime, and a set of
200 /// types.
201 #[derive(Debug, HashStable_Generic)]
202 pub struct PathSegment<'hir> {
203 /// The identifier portion of this path segment.
204 #[stable_hasher(project(name))]
205 pub ident: Ident,
206 // `id` and `res` are optional. We currently only use these in save-analysis,
207 // any path segments without these will not have save-analysis info and
208 // therefore will not have 'jump to def' in IDEs, but otherwise will not be
209 // affected. (In general, we don't bother to get the defs for synthesized
210 // segments, only for segments which have come from the AST).
211 pub hir_id: Option<HirId>,
212 pub res: Option<Res>,
213
214 /// Type/lifetime parameters attached to this path. They come in
215 /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. Note that
216 /// this is more than just simple syntactic sugar; the use of
217 /// parens affects the region binding rules, so we preserve the
218 /// distinction.
219 pub args: Option<&'hir GenericArgs<'hir>>,
220
221 /// Whether to infer remaining type parameters, if any.
222 /// This only applies to expression and pattern paths, and
223 /// out of those only the segments with no type parameters
224 /// to begin with, e.g., `Vec::new` is `<Vec<..>>::new::<..>`.
225 pub infer_args: bool,
226 }
227
228 impl<'hir> PathSegment<'hir> {
229 /// Converts an identifier to the corresponding segment.
230 pub fn from_ident(ident: Ident) -> PathSegment<'hir> {
231 PathSegment { ident, hir_id: None, res: None, infer_args: true, args: None }
232 }
233
234 pub fn generic_args(&self) -> &GenericArgs<'hir> {
235 if let Some(ref args) = self.args {
236 args
237 } else {
238 const DUMMY: &GenericArgs<'_> = &GenericArgs::none();
239 DUMMY
240 }
241 }
242 }
243
244 #[derive(Encodable, Debug, HashStable_Generic)]
245 pub struct ConstArg {
246 pub value: AnonConst,
247 pub span: Span,
248 }
249
250 #[derive(Debug, HashStable_Generic)]
251 pub enum GenericArg<'hir> {
252 Lifetime(Lifetime),
253 Type(Ty<'hir>),
254 Const(ConstArg),
255 }
256
257 impl GenericArg<'_> {
258 pub fn span(&self) -> Span {
259 match self {
260 GenericArg::Lifetime(l) => l.span,
261 GenericArg::Type(t) => t.span,
262 GenericArg::Const(c) => c.span,
263 }
264 }
265
266 pub fn id(&self) -> HirId {
267 match self {
268 GenericArg::Lifetime(l) => l.hir_id,
269 GenericArg::Type(t) => t.hir_id,
270 GenericArg::Const(c) => c.value.hir_id,
271 }
272 }
273
274 pub fn is_const(&self) -> bool {
275 matches!(self, GenericArg::Const(_))
276 }
277
278 pub fn descr(&self) -> &'static str {
279 match self {
280 GenericArg::Lifetime(_) => "lifetime",
281 GenericArg::Type(_) => "type",
282 GenericArg::Const(_) => "constant",
283 }
284 }
285 }
286
287 #[derive(Debug, HashStable_Generic)]
288 pub struct GenericArgs<'hir> {
289 /// The generic arguments for this path segment.
290 pub args: &'hir [GenericArg<'hir>],
291 /// Bindings (equality constraints) on associated types, if present.
292 /// E.g., `Foo<A = Bar>`.
293 pub bindings: &'hir [TypeBinding<'hir>],
294 /// Were arguments written in parenthesized form `Fn(T) -> U`?
295 /// This is required mostly for pretty-printing and diagnostics,
296 /// but also for changing lifetime elision rules to be "function-like".
297 pub parenthesized: bool,
298 }
299
300 impl GenericArgs<'_> {
301 pub const fn none() -> Self {
302 Self { args: &[], bindings: &[], parenthesized: false }
303 }
304
305 pub fn inputs(&self) -> &[Ty<'_>] {
306 if self.parenthesized {
307 for arg in self.args {
308 match arg {
309 GenericArg::Lifetime(_) => {}
310 GenericArg::Type(ref ty) => {
311 if let TyKind::Tup(ref tys) = ty.kind {
312 return tys;
313 }
314 break;
315 }
316 GenericArg::Const(_) => {}
317 }
318 }
319 }
320 panic!("GenericArgs::inputs: not a `Fn(T) -> U`");
321 }
322
323 pub fn own_counts(&self) -> GenericParamCount {
324 // We could cache this as a property of `GenericParamCount`, but
325 // the aim is to refactor this away entirely eventually and the
326 // presence of this method will be a constant reminder.
327 let mut own_counts: GenericParamCount = Default::default();
328
329 for arg in self.args {
330 match arg {
331 GenericArg::Lifetime(_) => own_counts.lifetimes += 1,
332 GenericArg::Type(_) => own_counts.types += 1,
333 GenericArg::Const(_) => own_counts.consts += 1,
334 };
335 }
336
337 own_counts
338 }
339 }
340
341 /// A modifier on a bound, currently this is only used for `?Sized`, where the
342 /// modifier is `Maybe`. Negative bounds should also be handled here.
343 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
344 #[derive(HashStable_Generic)]
345 pub enum TraitBoundModifier {
346 None,
347 Maybe,
348 MaybeConst,
349 }
350
351 /// The AST represents all type param bounds as types.
352 /// `typeck::collect::compute_bounds` matches these against
353 /// the "special" built-in traits (see `middle::lang_items`) and
354 /// detects `Copy`, `Send` and `Sync`.
355 #[derive(Debug, HashStable_Generic)]
356 pub enum GenericBound<'hir> {
357 Trait(PolyTraitRef<'hir>, TraitBoundModifier),
358 // FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
359 LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
360 Outlives(Lifetime),
361 }
362
363 impl GenericBound<'_> {
364 pub fn trait_ref(&self) -> Option<&TraitRef<'_>> {
365 match self {
366 GenericBound::Trait(data, _) => Some(&data.trait_ref),
367 _ => None,
368 }
369 }
370
371 pub fn span(&self) -> Span {
372 match self {
373 &GenericBound::Trait(ref t, ..) => t.span,
374 &GenericBound::LangItemTrait(_, span, ..) => span,
375 &GenericBound::Outlives(ref l) => l.span,
376 }
377 }
378 }
379
380 pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>];
381
382 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
383 pub enum LifetimeParamKind {
384 // Indicates that the lifetime definition was explicitly declared (e.g., in
385 // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`).
386 Explicit,
387
388 // Indicates that the lifetime definition was synthetically added
389 // as a result of an in-band lifetime usage (e.g., in
390 // `fn foo(x: &'a u8) -> &'a u8 { x }`).
391 InBand,
392
393 // Indication that the lifetime was elided (e.g., in both cases in
394 // `fn foo(x: &u8) -> &'_ u8 { x }`).
395 Elided,
396
397 // Indication that the lifetime name was somehow in error.
398 Error,
399 }
400
401 #[derive(Debug, HashStable_Generic)]
402 pub enum GenericParamKind<'hir> {
403 /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
404 Lifetime {
405 kind: LifetimeParamKind,
406 },
407 Type {
408 default: Option<&'hir Ty<'hir>>,
409 synthetic: Option<SyntheticTyParamKind>,
410 },
411 Const {
412 ty: &'hir Ty<'hir>,
413 },
414 }
415
416 #[derive(Debug, HashStable_Generic)]
417 pub struct GenericParam<'hir> {
418 pub hir_id: HirId,
419 pub name: ParamName,
420 pub attrs: &'hir [Attribute],
421 pub bounds: GenericBounds<'hir>,
422 pub span: Span,
423 pub pure_wrt_drop: bool,
424 pub kind: GenericParamKind<'hir>,
425 }
426
427 impl GenericParam<'hir> {
428 pub fn bounds_span(&self) -> Option<Span> {
429 self.bounds.iter().fold(None, |span, bound| {
430 let span = span.map(|s| s.to(bound.span())).unwrap_or_else(|| bound.span());
431
432 Some(span)
433 })
434 }
435 }
436
437 #[derive(Default)]
438 pub struct GenericParamCount {
439 pub lifetimes: usize,
440 pub types: usize,
441 pub consts: usize,
442 }
443
444 /// Represents lifetimes and type parameters attached to a declaration
445 /// of a function, enum, trait, etc.
446 #[derive(Debug, HashStable_Generic)]
447 pub struct Generics<'hir> {
448 pub params: &'hir [GenericParam<'hir>],
449 pub where_clause: WhereClause<'hir>,
450 pub span: Span,
451 }
452
453 impl Generics<'hir> {
454 pub const fn empty() -> Generics<'hir> {
455 Generics {
456 params: &[],
457 where_clause: WhereClause { predicates: &[], span: DUMMY_SP },
458 span: DUMMY_SP,
459 }
460 }
461
462 pub fn get_named(&self, name: Symbol) -> Option<&GenericParam<'_>> {
463 for param in self.params {
464 if name == param.name.ident().name {
465 return Some(param);
466 }
467 }
468 None
469 }
470
471 pub fn spans(&self) -> MultiSpan {
472 if self.params.is_empty() {
473 self.span.into()
474 } else {
475 self.params.iter().map(|p| p.span).collect::<Vec<Span>>().into()
476 }
477 }
478 }
479
480 /// Synthetic type parameters are converted to another form during lowering; this allows
481 /// us to track the original form they had, and is useful for error messages.
482 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
483 #[derive(HashStable_Generic)]
484 pub enum SyntheticTyParamKind {
485 ImplTrait,
486 // Created by the `#[rustc_synthetic]` attribute.
487 FromAttr,
488 }
489
490 /// A where-clause in a definition.
491 #[derive(Debug, HashStable_Generic)]
492 pub struct WhereClause<'hir> {
493 pub predicates: &'hir [WherePredicate<'hir>],
494 // Only valid if predicates aren't empty.
495 pub span: Span,
496 }
497
498 impl WhereClause<'_> {
499 pub fn span(&self) -> Option<Span> {
500 if self.predicates.is_empty() { None } else { Some(self.span) }
501 }
502
503 /// The `WhereClause` under normal circumstances points at either the predicates or the empty
504 /// space where the `where` clause should be. Only of use for diagnostic suggestions.
505 pub fn span_for_predicates_or_empty_place(&self) -> Span {
506 self.span
507 }
508
509 /// `Span` where further predicates would be suggested, accounting for trailing commas, like
510 /// in `fn foo<T>(t: T) where T: Foo,` so we don't suggest two trailing commas.
511 pub fn tail_span_for_suggestion(&self) -> Span {
512 let end = self.span_for_predicates_or_empty_place().shrink_to_hi();
513 self.predicates.last().map(|p| p.span()).unwrap_or(end).shrink_to_hi().to(end)
514 }
515 }
516
517 /// A single predicate in a where-clause.
518 #[derive(Debug, HashStable_Generic)]
519 pub enum WherePredicate<'hir> {
520 /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
521 BoundPredicate(WhereBoundPredicate<'hir>),
522 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
523 RegionPredicate(WhereRegionPredicate<'hir>),
524 /// An equality predicate (unsupported).
525 EqPredicate(WhereEqPredicate<'hir>),
526 }
527
528 impl WherePredicate<'_> {
529 pub fn span(&self) -> Span {
530 match self {
531 &WherePredicate::BoundPredicate(ref p) => p.span,
532 &WherePredicate::RegionPredicate(ref p) => p.span,
533 &WherePredicate::EqPredicate(ref p) => p.span,
534 }
535 }
536 }
537
538 /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`).
539 #[derive(Debug, HashStable_Generic)]
540 pub struct WhereBoundPredicate<'hir> {
541 pub span: Span,
542 /// Any generics from a `for` binding.
543 pub bound_generic_params: &'hir [GenericParam<'hir>],
544 /// The type being bounded.
545 pub bounded_ty: &'hir Ty<'hir>,
546 /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`).
547 pub bounds: GenericBounds<'hir>,
548 }
549
550 /// A lifetime predicate (e.g., `'a: 'b + 'c`).
551 #[derive(Debug, HashStable_Generic)]
552 pub struct WhereRegionPredicate<'hir> {
553 pub span: Span,
554 pub lifetime: Lifetime,
555 pub bounds: GenericBounds<'hir>,
556 }
557
558 /// An equality predicate (e.g., `T = int`); currently unsupported.
559 #[derive(Debug, HashStable_Generic)]
560 pub struct WhereEqPredicate<'hir> {
561 pub hir_id: HirId,
562 pub span: Span,
563 pub lhs_ty: &'hir Ty<'hir>,
564 pub rhs_ty: &'hir Ty<'hir>,
565 }
566
567 #[derive(Encodable, Debug, HashStable_Generic)]
568 pub struct ModuleItems {
569 // Use BTreeSets here so items are in the same order as in the
570 // list of all items in Crate
571 pub items: BTreeSet<HirId>,
572 pub trait_items: BTreeSet<TraitItemId>,
573 pub impl_items: BTreeSet<ImplItemId>,
574 }
575
576 /// A type representing only the top-level module.
577 #[derive(Encodable, Debug, HashStable_Generic)]
578 pub struct CrateItem<'hir> {
579 pub module: Mod<'hir>,
580 pub attrs: &'hir [Attribute],
581 pub span: Span,
582 }
583
584 /// The top-level data structure that stores the entire contents of
585 /// the crate currently being compiled.
586 ///
587 /// For more details, see the [rustc dev guide].
588 ///
589 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
590 #[derive(Debug)]
591 pub struct Crate<'hir> {
592 pub item: CrateItem<'hir>,
593 pub exported_macros: &'hir [MacroDef<'hir>],
594 // Attributes from non-exported macros, kept only for collecting the library feature list.
595 pub non_exported_macro_attrs: &'hir [Attribute],
596
597 // N.B., we use a `BTreeMap` here so that `visit_all_items` iterates
598 // over the ids in increasing order. In principle it should not
599 // matter what order we visit things in, but in *practice* it
600 // does, because it can affect the order in which errors are
601 // detected, which in turn can make compile-fail tests yield
602 // slightly different results.
603 pub items: BTreeMap<HirId, Item<'hir>>,
604
605 pub trait_items: BTreeMap<TraitItemId, TraitItem<'hir>>,
606 pub impl_items: BTreeMap<ImplItemId, ImplItem<'hir>>,
607 pub bodies: BTreeMap<BodyId, Body<'hir>>,
608 pub trait_impls: BTreeMap<DefId, Vec<HirId>>,
609
610 /// A list of the body ids written out in the order in which they
611 /// appear in the crate. If you're going to process all the bodies
612 /// in the crate, you should iterate over this list rather than the keys
613 /// of bodies.
614 pub body_ids: Vec<BodyId>,
615
616 /// A list of modules written out in the order in which they
617 /// appear in the crate. This includes the main crate module.
618 pub modules: BTreeMap<HirId, ModuleItems>,
619 /// A list of proc macro HirIds, written out in the order in which
620 /// they are declared in the static array generated by proc_macro_harness.
621 pub proc_macros: Vec<HirId>,
622
623 pub trait_map: BTreeMap<HirId, Vec<TraitCandidate>>,
624 }
625
626 impl Crate<'hir> {
627 pub fn item(&self, id: HirId) -> &Item<'hir> {
628 &self.items[&id]
629 }
630
631 pub fn trait_item(&self, id: TraitItemId) -> &TraitItem<'hir> {
632 &self.trait_items[&id]
633 }
634
635 pub fn impl_item(&self, id: ImplItemId) -> &ImplItem<'hir> {
636 &self.impl_items[&id]
637 }
638
639 pub fn body(&self, id: BodyId) -> &Body<'hir> {
640 &self.bodies[&id]
641 }
642 }
643
644 impl Crate<'_> {
645 /// Visits all items in the crate in some deterministic (but
646 /// unspecified) order. If you just need to process every item,
647 /// but don't care about nesting, this method is the best choice.
648 ///
649 /// If you do care about nesting -- usually because your algorithm
650 /// follows lexical scoping rules -- then you want a different
651 /// approach. You should override `visit_nested_item` in your
652 /// visitor and then call `intravisit::walk_crate` instead.
653 pub fn visit_all_item_likes<'hir, V>(&'hir self, visitor: &mut V)
654 where
655 V: itemlikevisit::ItemLikeVisitor<'hir>,
656 {
657 for item in self.items.values() {
658 visitor.visit_item(item);
659 }
660
661 for trait_item in self.trait_items.values() {
662 visitor.visit_trait_item(trait_item);
663 }
664
665 for impl_item in self.impl_items.values() {
666 visitor.visit_impl_item(impl_item);
667 }
668 }
669
670 /// A parallel version of `visit_all_item_likes`.
671 pub fn par_visit_all_item_likes<'hir, V>(&'hir self, visitor: &V)
672 where
673 V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send,
674 {
675 parallel!(
676 {
677 par_for_each_in(&self.items, |(_, item)| {
678 visitor.visit_item(item);
679 });
680 },
681 {
682 par_for_each_in(&self.trait_items, |(_, trait_item)| {
683 visitor.visit_trait_item(trait_item);
684 });
685 },
686 {
687 par_for_each_in(&self.impl_items, |(_, impl_item)| {
688 visitor.visit_impl_item(impl_item);
689 });
690 }
691 );
692 }
693 }
694
695 /// A macro definition, in this crate or imported from another.
696 ///
697 /// Not parsed directly, but created on macro import or `macro_rules!` expansion.
698 #[derive(Debug, HashStable_Generic)]
699 pub struct MacroDef<'hir> {
700 pub ident: Ident,
701 pub vis: Visibility<'hir>,
702 pub attrs: &'hir [Attribute],
703 pub hir_id: HirId,
704 pub span: Span,
705 pub ast: ast::MacroDef,
706 }
707
708 /// A block of statements `{ .. }`, which may have a label (in this case the
709 /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of
710 /// the `rules` being anything but `DefaultBlock`.
711 #[derive(Debug, HashStable_Generic)]
712 pub struct Block<'hir> {
713 /// Statements in a block.
714 pub stmts: &'hir [Stmt<'hir>],
715 /// An expression at the end of the block
716 /// without a semicolon, if any.
717 pub expr: Option<&'hir Expr<'hir>>,
718 #[stable_hasher(ignore)]
719 pub hir_id: HirId,
720 /// Distinguishes between `unsafe { ... }` and `{ ... }`.
721 pub rules: BlockCheckMode,
722 pub span: Span,
723 /// If true, then there may exist `break 'a` values that aim to
724 /// break out of this block early.
725 /// Used by `'label: {}` blocks and by `try {}` blocks.
726 pub targeted_by_break: bool,
727 }
728
729 #[derive(Debug, HashStable_Generic)]
730 pub struct Pat<'hir> {
731 #[stable_hasher(ignore)]
732 pub hir_id: HirId,
733 pub kind: PatKind<'hir>,
734 pub span: Span,
735 // Whether to use default binding modes.
736 // At present, this is false only for destructuring assignment.
737 pub default_binding_modes: bool,
738 }
739
740 impl Pat<'_> {
741 // FIXME(#19596) this is a workaround, but there should be a better way
742 fn walk_short_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) -> bool {
743 if !it(self) {
744 return false;
745 }
746
747 use PatKind::*;
748 match &self.kind {
749 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => true,
750 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_short_(it),
751 Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk_short_(it)),
752 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().all(|p| p.walk_short_(it)),
753 Slice(before, slice, after) => {
754 before.iter().chain(slice.iter()).chain(after.iter()).all(|p| p.walk_short_(it))
755 }
756 }
757 }
758
759 /// Walk the pattern in left-to-right order,
760 /// short circuiting (with `.all(..)`) if `false` is returned.
761 ///
762 /// Note that when visiting e.g. `Tuple(ps)`,
763 /// if visiting `ps[0]` returns `false`,
764 /// then `ps[1]` will not be visited.
765 pub fn walk_short(&self, mut it: impl FnMut(&Pat<'_>) -> bool) -> bool {
766 self.walk_short_(&mut it)
767 }
768
769 // FIXME(#19596) this is a workaround, but there should be a better way
770 fn walk_(&self, it: &mut impl FnMut(&Pat<'_>) -> bool) {
771 if !it(self) {
772 return;
773 }
774
775 use PatKind::*;
776 match &self.kind {
777 Wild | Lit(_) | Range(..) | Binding(.., None) | Path(_) => {}
778 Box(s) | Ref(s, _) | Binding(.., Some(s)) => s.walk_(it),
779 Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk_(it)),
780 TupleStruct(_, s, _) | Tuple(s, _) | Or(s) => s.iter().for_each(|p| p.walk_(it)),
781 Slice(before, slice, after) => {
782 before.iter().chain(slice.iter()).chain(after.iter()).for_each(|p| p.walk_(it))
783 }
784 }
785 }
786
787 /// Walk the pattern in left-to-right order.
788 ///
789 /// If `it(pat)` returns `false`, the children are not visited.
790 pub fn walk(&self, mut it: impl FnMut(&Pat<'_>) -> bool) {
791 self.walk_(&mut it)
792 }
793
794 /// Walk the pattern in left-to-right order.
795 ///
796 /// If you always want to recurse, prefer this method over `walk`.
797 pub fn walk_always(&self, mut it: impl FnMut(&Pat<'_>)) {
798 self.walk(|p| {
799 it(p);
800 true
801 })
802 }
803 }
804
805 /// A single field in a struct pattern.
806 ///
807 /// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
808 /// are treated the same as` x: x, y: ref y, z: ref mut z`,
809 /// except `is_shorthand` is true.
810 #[derive(Debug, HashStable_Generic)]
811 pub struct FieldPat<'hir> {
812 #[stable_hasher(ignore)]
813 pub hir_id: HirId,
814 /// The identifier for the field.
815 #[stable_hasher(project(name))]
816 pub ident: Ident,
817 /// The pattern the field is destructured to.
818 pub pat: &'hir Pat<'hir>,
819 pub is_shorthand: bool,
820 pub span: Span,
821 }
822
823 /// Explicit binding annotations given in the HIR for a binding. Note
824 /// that this is not the final binding *mode* that we infer after type
825 /// inference.
826 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
827 pub enum BindingAnnotation {
828 /// No binding annotation given: this means that the final binding mode
829 /// will depend on whether we have skipped through a `&` reference
830 /// when matching. For example, the `x` in `Some(x)` will have binding
831 /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
832 /// ultimately be inferred to be by-reference.
833 ///
834 /// Note that implicit reference skipping is not implemented yet (#42640).
835 Unannotated,
836
837 /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
838 Mutable,
839
840 /// Annotated as `ref`, like `ref x`
841 Ref,
842
843 /// Annotated as `ref mut x`.
844 RefMut,
845 }
846
847 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
848 pub enum RangeEnd {
849 Included,
850 Excluded,
851 }
852
853 impl fmt::Display for RangeEnd {
854 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855 f.write_str(match self {
856 RangeEnd::Included => "..=",
857 RangeEnd::Excluded => "..",
858 })
859 }
860 }
861
862 #[derive(Debug, HashStable_Generic)]
863 pub enum PatKind<'hir> {
864 /// Represents a wildcard pattern (i.e., `_`).
865 Wild,
866
867 /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`.
868 /// The `HirId` is the canonical ID for the variable being bound,
869 /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID),
870 /// which is the pattern ID of the first `x`.
871 Binding(BindingAnnotation, HirId, Ident, Option<&'hir Pat<'hir>>),
872
873 /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
874 /// The `bool` is `true` in the presence of a `..`.
875 Struct(QPath<'hir>, &'hir [FieldPat<'hir>], bool),
876
877 /// A tuple struct/variant pattern `Variant(x, y, .., z)`.
878 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
879 /// `0 <= position <= subpats.len()`
880 TupleStruct(QPath<'hir>, &'hir [&'hir Pat<'hir>], Option<usize>),
881
882 /// An or-pattern `A | B | C`.
883 /// Invariant: `pats.len() >= 2`.
884 Or(&'hir [&'hir Pat<'hir>]),
885
886 /// A path pattern for an unit struct/variant or a (maybe-associated) constant.
887 Path(QPath<'hir>),
888
889 /// A tuple pattern (e.g., `(a, b)`).
890 /// If the `..` pattern fragment is present, then `Option<usize>` denotes its position.
891 /// `0 <= position <= subpats.len()`
892 Tuple(&'hir [&'hir Pat<'hir>], Option<usize>),
893
894 /// A `box` pattern.
895 Box(&'hir Pat<'hir>),
896
897 /// A reference pattern (e.g., `&mut (a, b)`).
898 Ref(&'hir Pat<'hir>, Mutability),
899
900 /// A literal.
901 Lit(&'hir Expr<'hir>),
902
903 /// A range pattern (e.g., `1..=2` or `1..2`).
904 Range(Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>, RangeEnd),
905
906 /// A slice pattern, `[before_0, ..., before_n, (slice, after_0, ..., after_n)?]`.
907 ///
908 /// Here, `slice` is lowered from the syntax `($binding_mode $ident @)? ..`.
909 /// If `slice` exists, then `after` can be non-empty.
910 ///
911 /// The representation for e.g., `[a, b, .., c, d]` is:
912 /// ```
913 /// PatKind::Slice([Binding(a), Binding(b)], Some(Wild), [Binding(c), Binding(d)])
914 /// ```
915 Slice(&'hir [&'hir Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [&'hir Pat<'hir>]),
916 }
917
918 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
919 pub enum BinOpKind {
920 /// The `+` operator (addition).
921 Add,
922 /// The `-` operator (subtraction).
923 Sub,
924 /// The `*` operator (multiplication).
925 Mul,
926 /// The `/` operator (division).
927 Div,
928 /// The `%` operator (modulus).
929 Rem,
930 /// The `&&` operator (logical and).
931 And,
932 /// The `||` operator (logical or).
933 Or,
934 /// The `^` operator (bitwise xor).
935 BitXor,
936 /// The `&` operator (bitwise and).
937 BitAnd,
938 /// The `|` operator (bitwise or).
939 BitOr,
940 /// The `<<` operator (shift left).
941 Shl,
942 /// The `>>` operator (shift right).
943 Shr,
944 /// The `==` operator (equality).
945 Eq,
946 /// The `<` operator (less than).
947 Lt,
948 /// The `<=` operator (less than or equal to).
949 Le,
950 /// The `!=` operator (not equal to).
951 Ne,
952 /// The `>=` operator (greater than or equal to).
953 Ge,
954 /// The `>` operator (greater than).
955 Gt,
956 }
957
958 impl BinOpKind {
959 pub fn as_str(self) -> &'static str {
960 match self {
961 BinOpKind::Add => "+",
962 BinOpKind::Sub => "-",
963 BinOpKind::Mul => "*",
964 BinOpKind::Div => "/",
965 BinOpKind::Rem => "%",
966 BinOpKind::And => "&&",
967 BinOpKind::Or => "||",
968 BinOpKind::BitXor => "^",
969 BinOpKind::BitAnd => "&",
970 BinOpKind::BitOr => "|",
971 BinOpKind::Shl => "<<",
972 BinOpKind::Shr => ">>",
973 BinOpKind::Eq => "==",
974 BinOpKind::Lt => "<",
975 BinOpKind::Le => "<=",
976 BinOpKind::Ne => "!=",
977 BinOpKind::Ge => ">=",
978 BinOpKind::Gt => ">",
979 }
980 }
981
982 pub fn is_lazy(self) -> bool {
983 matches!(self, BinOpKind::And | BinOpKind::Or)
984 }
985
986 pub fn is_shift(self) -> bool {
987 matches!(self, BinOpKind::Shl | BinOpKind::Shr)
988 }
989
990 pub fn is_comparison(self) -> bool {
991 match self {
992 BinOpKind::Eq
993 | BinOpKind::Lt
994 | BinOpKind::Le
995 | BinOpKind::Ne
996 | BinOpKind::Gt
997 | BinOpKind::Ge => true,
998 BinOpKind::And
999 | BinOpKind::Or
1000 | BinOpKind::Add
1001 | BinOpKind::Sub
1002 | BinOpKind::Mul
1003 | BinOpKind::Div
1004 | BinOpKind::Rem
1005 | BinOpKind::BitXor
1006 | BinOpKind::BitAnd
1007 | BinOpKind::BitOr
1008 | BinOpKind::Shl
1009 | BinOpKind::Shr => false,
1010 }
1011 }
1012
1013 /// Returns `true` if the binary operator takes its arguments by value.
1014 pub fn is_by_value(self) -> bool {
1015 !self.is_comparison()
1016 }
1017 }
1018
1019 impl Into<ast::BinOpKind> for BinOpKind {
1020 fn into(self) -> ast::BinOpKind {
1021 match self {
1022 BinOpKind::Add => ast::BinOpKind::Add,
1023 BinOpKind::Sub => ast::BinOpKind::Sub,
1024 BinOpKind::Mul => ast::BinOpKind::Mul,
1025 BinOpKind::Div => ast::BinOpKind::Div,
1026 BinOpKind::Rem => ast::BinOpKind::Rem,
1027 BinOpKind::And => ast::BinOpKind::And,
1028 BinOpKind::Or => ast::BinOpKind::Or,
1029 BinOpKind::BitXor => ast::BinOpKind::BitXor,
1030 BinOpKind::BitAnd => ast::BinOpKind::BitAnd,
1031 BinOpKind::BitOr => ast::BinOpKind::BitOr,
1032 BinOpKind::Shl => ast::BinOpKind::Shl,
1033 BinOpKind::Shr => ast::BinOpKind::Shr,
1034 BinOpKind::Eq => ast::BinOpKind::Eq,
1035 BinOpKind::Lt => ast::BinOpKind::Lt,
1036 BinOpKind::Le => ast::BinOpKind::Le,
1037 BinOpKind::Ne => ast::BinOpKind::Ne,
1038 BinOpKind::Ge => ast::BinOpKind::Ge,
1039 BinOpKind::Gt => ast::BinOpKind::Gt,
1040 }
1041 }
1042 }
1043
1044 pub type BinOp = Spanned<BinOpKind>;
1045
1046 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1047 pub enum UnOp {
1048 /// The `*` operator (deferencing).
1049 UnDeref,
1050 /// The `!` operator (logical negation).
1051 UnNot,
1052 /// The `-` operator (negation).
1053 UnNeg,
1054 }
1055
1056 impl UnOp {
1057 pub fn as_str(self) -> &'static str {
1058 match self {
1059 Self::UnDeref => "*",
1060 Self::UnNot => "!",
1061 Self::UnNeg => "-",
1062 }
1063 }
1064
1065 /// Returns `true` if the unary operator takes its argument by value.
1066 pub fn is_by_value(self) -> bool {
1067 matches!(self, Self::UnNeg | Self::UnNot)
1068 }
1069 }
1070
1071 /// A statement.
1072 #[derive(Debug, HashStable_Generic)]
1073 pub struct Stmt<'hir> {
1074 pub hir_id: HirId,
1075 pub kind: StmtKind<'hir>,
1076 pub span: Span,
1077 }
1078
1079 /// The contents of a statement.
1080 #[derive(Debug, HashStable_Generic)]
1081 pub enum StmtKind<'hir> {
1082 /// A local (`let`) binding.
1083 Local(&'hir Local<'hir>),
1084
1085 /// An item binding.
1086 Item(ItemId),
1087
1088 /// An expression without a trailing semi-colon (must have unit type).
1089 Expr(&'hir Expr<'hir>),
1090
1091 /// An expression with a trailing semi-colon (may have any type).
1092 Semi(&'hir Expr<'hir>),
1093 }
1094
1095 impl<'hir> StmtKind<'hir> {
1096 pub fn attrs(&self, get_item: impl FnOnce(ItemId) -> &'hir Item<'hir>) -> &'hir [Attribute] {
1097 match *self {
1098 StmtKind::Local(ref l) => &l.attrs,
1099 StmtKind::Item(ref item_id) => &get_item(*item_id).attrs,
1100 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => &e.attrs,
1101 }
1102 }
1103 }
1104
1105 /// Represents a `let` statement (i.e., `let <pat>:<ty> = <expr>;`).
1106 #[derive(Debug, HashStable_Generic)]
1107 pub struct Local<'hir> {
1108 pub pat: &'hir Pat<'hir>,
1109 /// Type annotation, if any (otherwise the type will be inferred).
1110 pub ty: Option<&'hir Ty<'hir>>,
1111 /// Initializer expression to set the value, if any.
1112 pub init: Option<&'hir Expr<'hir>>,
1113 pub hir_id: HirId,
1114 pub span: Span,
1115 pub attrs: AttrVec,
1116 /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop
1117 /// desugaring. Otherwise will be `Normal`.
1118 pub source: LocalSource,
1119 }
1120
1121 /// Represents a single arm of a `match` expression, e.g.
1122 /// `<pat> (if <guard>) => <body>`.
1123 #[derive(Debug, HashStable_Generic)]
1124 pub struct Arm<'hir> {
1125 #[stable_hasher(ignore)]
1126 pub hir_id: HirId,
1127 pub span: Span,
1128 pub attrs: &'hir [Attribute],
1129 /// If this pattern and the optional guard matches, then `body` is evaluated.
1130 pub pat: &'hir Pat<'hir>,
1131 /// Optional guard clause.
1132 pub guard: Option<Guard<'hir>>,
1133 /// The expression the arm evaluates to if this arm matches.
1134 pub body: &'hir Expr<'hir>,
1135 }
1136
1137 #[derive(Debug, HashStable_Generic)]
1138 pub enum Guard<'hir> {
1139 If(&'hir Expr<'hir>),
1140 }
1141
1142 #[derive(Debug, HashStable_Generic)]
1143 pub struct Field<'hir> {
1144 #[stable_hasher(ignore)]
1145 pub hir_id: HirId,
1146 pub ident: Ident,
1147 pub expr: &'hir Expr<'hir>,
1148 pub span: Span,
1149 pub is_shorthand: bool,
1150 }
1151
1152 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1153 pub enum BlockCheckMode {
1154 DefaultBlock,
1155 UnsafeBlock(UnsafeSource),
1156 PushUnsafeBlock(UnsafeSource),
1157 PopUnsafeBlock(UnsafeSource),
1158 }
1159
1160 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1161 pub enum UnsafeSource {
1162 CompilerGenerated,
1163 UserProvided,
1164 }
1165
1166 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Hash, Debug)]
1167 pub struct BodyId {
1168 pub hir_id: HirId,
1169 }
1170
1171 /// The body of a function, closure, or constant value. In the case of
1172 /// a function, the body contains not only the function body itself
1173 /// (which is an expression), but also the argument patterns, since
1174 /// those are something that the caller doesn't really care about.
1175 ///
1176 /// # Examples
1177 ///
1178 /// ```
1179 /// fn foo((x, y): (u32, u32)) -> u32 {
1180 /// x + y
1181 /// }
1182 /// ```
1183 ///
1184 /// Here, the `Body` associated with `foo()` would contain:
1185 ///
1186 /// - an `params` array containing the `(x, y)` pattern
1187 /// - a `value` containing the `x + y` expression (maybe wrapped in a block)
1188 /// - `generator_kind` would be `None`
1189 ///
1190 /// All bodies have an **owner**, which can be accessed via the HIR
1191 /// map using `body_owner_def_id()`.
1192 #[derive(Debug)]
1193 pub struct Body<'hir> {
1194 pub params: &'hir [Param<'hir>],
1195 pub value: Expr<'hir>,
1196 pub generator_kind: Option<GeneratorKind>,
1197 }
1198
1199 impl Body<'hir> {
1200 pub fn id(&self) -> BodyId {
1201 BodyId { hir_id: self.value.hir_id }
1202 }
1203
1204 pub fn generator_kind(&self) -> Option<GeneratorKind> {
1205 self.generator_kind
1206 }
1207 }
1208
1209 /// The type of source expression that caused this generator to be created.
1210 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1211 pub enum GeneratorKind {
1212 /// An explicit `async` block or the body of an async function.
1213 Async(AsyncGeneratorKind),
1214
1215 /// A generator literal created via a `yield` inside a closure.
1216 Gen,
1217 }
1218
1219 impl fmt::Display for GeneratorKind {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 match self {
1222 GeneratorKind::Async(k) => fmt::Display::fmt(k, f),
1223 GeneratorKind::Gen => f.write_str("generator"),
1224 }
1225 }
1226 }
1227
1228 /// In the case of a generator created as part of an async construct,
1229 /// which kind of async construct caused it to be created?
1230 ///
1231 /// This helps error messages but is also used to drive coercions in
1232 /// type-checking (see #60424).
1233 #[derive(Clone, PartialEq, Eq, HashStable_Generic, Encodable, Decodable, Debug, Copy)]
1234 pub enum AsyncGeneratorKind {
1235 /// An explicit `async` block written by the user.
1236 Block,
1237
1238 /// An explicit `async` block written by the user.
1239 Closure,
1240
1241 /// The `async` block generated as the body of an async function.
1242 Fn,
1243 }
1244
1245 impl fmt::Display for AsyncGeneratorKind {
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 f.write_str(match self {
1248 AsyncGeneratorKind::Block => "`async` block",
1249 AsyncGeneratorKind::Closure => "`async` closure body",
1250 AsyncGeneratorKind::Fn => "`async fn` body",
1251 })
1252 }
1253 }
1254
1255 #[derive(Copy, Clone, Debug)]
1256 pub enum BodyOwnerKind {
1257 /// Functions and methods.
1258 Fn,
1259
1260 /// Closures
1261 Closure,
1262
1263 /// Constants and associated constants.
1264 Const,
1265
1266 /// Initializer of a `static` item.
1267 Static(Mutability),
1268 }
1269
1270 impl BodyOwnerKind {
1271 pub fn is_fn_or_closure(self) -> bool {
1272 match self {
1273 BodyOwnerKind::Fn | BodyOwnerKind::Closure => true,
1274 BodyOwnerKind::Const | BodyOwnerKind::Static(_) => false,
1275 }
1276 }
1277 }
1278
1279 /// The kind of an item that requires const-checking.
1280 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1281 pub enum ConstContext {
1282 /// A `const fn`.
1283 ConstFn,
1284
1285 /// A `static` or `static mut`.
1286 Static(Mutability),
1287
1288 /// A `const`, associated `const`, or other const context.
1289 ///
1290 /// Other contexts include:
1291 /// - Array length expressions
1292 /// - Enum discriminants
1293 /// - Const generics
1294 ///
1295 /// For the most part, other contexts are treated just like a regular `const`, so they are
1296 /// lumped into the same category.
1297 Const,
1298 }
1299
1300 impl ConstContext {
1301 /// A description of this const context that can appear between backticks in an error message.
1302 ///
1303 /// E.g. `const` or `static mut`.
1304 pub fn keyword_name(self) -> &'static str {
1305 match self {
1306 Self::Const => "const",
1307 Self::Static(Mutability::Not) => "static",
1308 Self::Static(Mutability::Mut) => "static mut",
1309 Self::ConstFn => "const fn",
1310 }
1311 }
1312 }
1313
1314 /// A colloquial, trivially pluralizable description of this const context for use in error
1315 /// messages.
1316 impl fmt::Display for ConstContext {
1317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318 match *self {
1319 Self::Const => write!(f, "constant"),
1320 Self::Static(_) => write!(f, "static"),
1321 Self::ConstFn => write!(f, "constant function"),
1322 }
1323 }
1324 }
1325
1326 /// A literal.
1327 pub type Lit = Spanned<LitKind>;
1328
1329 /// A constant (expression) that's not an item or associated item,
1330 /// but needs its own `DefId` for type-checking, const-eval, etc.
1331 /// These are usually found nested inside types (e.g., array lengths)
1332 /// or expressions (e.g., repeat counts), and also used to define
1333 /// explicit discriminant values for enum variants.
1334 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)]
1335 pub struct AnonConst {
1336 pub hir_id: HirId,
1337 pub body: BodyId,
1338 }
1339
1340 /// An expression.
1341 #[derive(Debug)]
1342 pub struct Expr<'hir> {
1343 pub hir_id: HirId,
1344 pub kind: ExprKind<'hir>,
1345 pub attrs: AttrVec,
1346 pub span: Span,
1347 }
1348
1349 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1350 #[cfg(target_arch = "x86_64")]
1351 rustc_data_structures::static_assert_size!(Expr<'static>, 72);
1352
1353 impl Expr<'_> {
1354 pub fn precedence(&self) -> ExprPrecedence {
1355 match self.kind {
1356 ExprKind::Box(_) => ExprPrecedence::Box,
1357 ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1358 ExprKind::Array(_) => ExprPrecedence::Array,
1359 ExprKind::Call(..) => ExprPrecedence::Call,
1360 ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1361 ExprKind::Tup(_) => ExprPrecedence::Tup,
1362 ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node.into()),
1363 ExprKind::Unary(..) => ExprPrecedence::Unary,
1364 ExprKind::Lit(_) => ExprPrecedence::Lit,
1365 ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1366 ExprKind::DropTemps(ref expr, ..) => expr.precedence(),
1367 ExprKind::Loop(..) => ExprPrecedence::Loop,
1368 ExprKind::Match(..) => ExprPrecedence::Match,
1369 ExprKind::Closure(..) => ExprPrecedence::Closure,
1370 ExprKind::Block(..) => ExprPrecedence::Block,
1371 ExprKind::Assign(..) => ExprPrecedence::Assign,
1372 ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1373 ExprKind::Field(..) => ExprPrecedence::Field,
1374 ExprKind::Index(..) => ExprPrecedence::Index,
1375 ExprKind::Path(..) => ExprPrecedence::Path,
1376 ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1377 ExprKind::Break(..) => ExprPrecedence::Break,
1378 ExprKind::Continue(..) => ExprPrecedence::Continue,
1379 ExprKind::Ret(..) => ExprPrecedence::Ret,
1380 ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1381 ExprKind::LlvmInlineAsm(..) => ExprPrecedence::InlineAsm,
1382 ExprKind::Struct(..) => ExprPrecedence::Struct,
1383 ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1384 ExprKind::Yield(..) => ExprPrecedence::Yield,
1385 ExprKind::Err => ExprPrecedence::Err,
1386 }
1387 }
1388
1389 // Whether this looks like a place expr, without checking for deref
1390 // adjustments.
1391 // This will return `true` in some potentially surprising cases such as
1392 // `CONSTANT.field`.
1393 pub fn is_syntactic_place_expr(&self) -> bool {
1394 self.is_place_expr(|_| true)
1395 }
1396
1397 /// Whether this is a place expression.
1398 ///
1399 /// `allow_projections_from` should return `true` if indexing a field or index expression based
1400 /// on the given expression should be considered a place expression.
1401 pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
1402 match self.kind {
1403 ExprKind::Path(QPath::Resolved(_, ref path)) => {
1404 matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
1405 }
1406
1407 // Type ascription inherits its place expression kind from its
1408 // operand. See:
1409 // https://github.com/rust-lang/rfcs/blob/master/text/0803-type-ascription.md#type-ascription-and-temporaries
1410 ExprKind::Type(ref e, _) => e.is_place_expr(allow_projections_from),
1411
1412 ExprKind::Unary(UnOp::UnDeref, _) => true,
1413
1414 ExprKind::Field(ref base, _) | ExprKind::Index(ref base, _) => {
1415 allow_projections_from(base) || base.is_place_expr(allow_projections_from)
1416 }
1417
1418 // Lang item paths cannot currently be local variables or statics.
1419 ExprKind::Path(QPath::LangItem(..)) => false,
1420
1421 // Partially qualified paths in expressions can only legally
1422 // refer to associated items which are always rvalues.
1423 ExprKind::Path(QPath::TypeRelative(..))
1424 | ExprKind::Call(..)
1425 | ExprKind::MethodCall(..)
1426 | ExprKind::Struct(..)
1427 | ExprKind::Tup(..)
1428 | ExprKind::Match(..)
1429 | ExprKind::Closure(..)
1430 | ExprKind::Block(..)
1431 | ExprKind::Repeat(..)
1432 | ExprKind::Array(..)
1433 | ExprKind::Break(..)
1434 | ExprKind::Continue(..)
1435 | ExprKind::Ret(..)
1436 | ExprKind::Loop(..)
1437 | ExprKind::Assign(..)
1438 | ExprKind::InlineAsm(..)
1439 | ExprKind::LlvmInlineAsm(..)
1440 | ExprKind::AssignOp(..)
1441 | ExprKind::Lit(_)
1442 | ExprKind::ConstBlock(..)
1443 | ExprKind::Unary(..)
1444 | ExprKind::Box(..)
1445 | ExprKind::AddrOf(..)
1446 | ExprKind::Binary(..)
1447 | ExprKind::Yield(..)
1448 | ExprKind::Cast(..)
1449 | ExprKind::DropTemps(..)
1450 | ExprKind::Err => false,
1451 }
1452 }
1453
1454 /// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
1455 /// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
1456 /// silent, only signaling the ownership system. By doing this, suggestions that check the
1457 /// `ExprKind` of any given `Expr` for presentation don't have to care about `DropTemps`
1458 /// beyond remembering to call this function before doing analysis on it.
1459 pub fn peel_drop_temps(&self) -> &Self {
1460 let mut expr = self;
1461 while let ExprKind::DropTemps(inner) = &expr.kind {
1462 expr = inner;
1463 }
1464 expr
1465 }
1466 }
1467
1468 /// Checks if the specified expression is a built-in range literal.
1469 /// (See: `LoweringContext::lower_expr()`).
1470 pub fn is_range_literal(expr: &Expr<'_>) -> bool {
1471 match expr.kind {
1472 // All built-in range literals but `..=` and `..` desugar to `Struct`s.
1473 ExprKind::Struct(ref qpath, _, _) => matches!(
1474 **qpath,
1475 QPath::LangItem(
1476 LangItem::Range
1477 | LangItem::RangeTo
1478 | LangItem::RangeFrom
1479 | LangItem::RangeFull
1480 | LangItem::RangeToInclusive,
1481 _,
1482 )
1483 ),
1484
1485 // `..=` desugars into `::std::ops::RangeInclusive::new(...)`.
1486 ExprKind::Call(ref func, _) => {
1487 matches!(func.kind, ExprKind::Path(QPath::LangItem(LangItem::RangeInclusiveNew, _)))
1488 }
1489
1490 _ => false,
1491 }
1492 }
1493
1494 #[derive(Debug, HashStable_Generic)]
1495 pub enum ExprKind<'hir> {
1496 /// A `box x` expression.
1497 Box(&'hir Expr<'hir>),
1498 /// Allow anonymous constants from an inline `const` block
1499 ConstBlock(AnonConst),
1500 /// An array (e.g., `[a, b, c, d]`).
1501 Array(&'hir [Expr<'hir>]),
1502 /// A function call.
1503 ///
1504 /// The first field resolves to the function itself (usually an `ExprKind::Path`),
1505 /// and the second field is the list of arguments.
1506 /// This also represents calling the constructor of
1507 /// tuple-like ADTs such as tuple structs and enum variants.
1508 Call(&'hir Expr<'hir>, &'hir [Expr<'hir>]),
1509 /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`).
1510 ///
1511 /// The `PathSegment`/`Span` represent the method name and its generic arguments
1512 /// (within the angle brackets).
1513 /// The first element of the vector of `Expr`s is the expression that evaluates
1514 /// to the object on which the method is being called on (the receiver),
1515 /// and the remaining elements are the rest of the arguments.
1516 /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1517 /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1518 /// The final `Span` represents the span of the function and arguments
1519 /// (e.g. `foo::<Bar, Baz>(a, b, c, d)` in `x.foo::<Bar, Baz>(a, b, c, d)`
1520 ///
1521 /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with
1522 /// the `hir_id` of the `MethodCall` node itself.
1523 ///
1524 /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id
1525 MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span),
1526 /// A tuple (e.g., `(a, b, c, d)`).
1527 Tup(&'hir [Expr<'hir>]),
1528 /// A binary operation (e.g., `a + b`, `a * b`).
1529 Binary(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1530 /// A unary operation (e.g., `!x`, `*x`).
1531 Unary(UnOp, &'hir Expr<'hir>),
1532 /// A literal (e.g., `1`, `"foo"`).
1533 Lit(Lit),
1534 /// A cast (e.g., `foo as f64`).
1535 Cast(&'hir Expr<'hir>, &'hir Ty<'hir>),
1536 /// A type reference (e.g., `Foo`).
1537 Type(&'hir Expr<'hir>, &'hir Ty<'hir>),
1538 /// Wraps the expression in a terminating scope.
1539 /// This makes it semantically equivalent to `{ let _t = expr; _t }`.
1540 ///
1541 /// This construct only exists to tweak the drop order in HIR lowering.
1542 /// An example of that is the desugaring of `for` loops.
1543 DropTemps(&'hir Expr<'hir>),
1544 /// A conditionless loop (can be exited with `break`, `continue`, or `return`).
1545 ///
1546 /// I.e., `'label: loop { <block> }`.
1547 Loop(&'hir Block<'hir>, Option<Label>, LoopSource),
1548 /// A `match` block, with a source that indicates whether or not it is
1549 /// the result of a desugaring, and if so, which kind.
1550 Match(&'hir Expr<'hir>, &'hir [Arm<'hir>], MatchSource),
1551 /// A closure (e.g., `move |a, b, c| {a + b + c}`).
1552 ///
1553 /// The `Span` is the argument block `|...|`.
1554 ///
1555 /// This may also be a generator literal or an `async block` as indicated by the
1556 /// `Option<Movability>`.
1557 Closure(CaptureBy, &'hir FnDecl<'hir>, BodyId, Span, Option<Movability>),
1558 /// A block (e.g., `'label: { ... }`).
1559 Block(&'hir Block<'hir>, Option<Label>),
1560
1561 /// An assignment (e.g., `a = foo()`).
1562 Assign(&'hir Expr<'hir>, &'hir Expr<'hir>, Span),
1563 /// An assignment with an operator.
1564 ///
1565 /// E.g., `a += 1`.
1566 AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
1567 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
1568 Field(&'hir Expr<'hir>, Ident),
1569 /// An indexing operation (`foo[2]`).
1570 Index(&'hir Expr<'hir>, &'hir Expr<'hir>),
1571
1572 /// Path to a definition, possibly containing lifetime or type parameters.
1573 Path(QPath<'hir>),
1574
1575 /// A referencing operation (i.e., `&a` or `&mut a`).
1576 AddrOf(BorrowKind, Mutability, &'hir Expr<'hir>),
1577 /// A `break`, with an optional label to break.
1578 Break(Destination, Option<&'hir Expr<'hir>>),
1579 /// A `continue`, with an optional label.
1580 Continue(Destination),
1581 /// A `return`, with an optional value to be returned.
1582 Ret(Option<&'hir Expr<'hir>>),
1583
1584 /// Inline assembly (from `asm!`), with its outputs and inputs.
1585 InlineAsm(&'hir InlineAsm<'hir>),
1586 /// Inline assembly (from `llvm_asm!`), with its outputs and inputs.
1587 LlvmInlineAsm(&'hir LlvmInlineAsm<'hir>),
1588
1589 /// A struct or struct-like variant literal expression.
1590 ///
1591 /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1592 /// where `base` is the `Option<Expr>`.
1593 Struct(&'hir QPath<'hir>, &'hir [Field<'hir>], Option<&'hir Expr<'hir>>),
1594
1595 /// An array literal constructed from one repeated element.
1596 ///
1597 /// E.g., `[1; 5]`. The first expression is the element
1598 /// to be repeated; the second is the number of times to repeat it.
1599 Repeat(&'hir Expr<'hir>, AnonConst),
1600
1601 /// A suspension point for generators (i.e., `yield <expr>`).
1602 Yield(&'hir Expr<'hir>, YieldSource),
1603
1604 /// A placeholder for an expression that wasn't syntactically well formed in some way.
1605 Err,
1606 }
1607
1608 /// Represents an optionally `Self`-qualified value/type path or associated extension.
1609 ///
1610 /// To resolve the path to a `DefId`, call [`qpath_res`].
1611 ///
1612 /// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res
1613 #[derive(Debug, HashStable_Generic)]
1614 pub enum QPath<'hir> {
1615 /// Path to a definition, optionally "fully-qualified" with a `Self`
1616 /// type, if the path points to an associated item in a trait.
1617 ///
1618 /// E.g., an unqualified path like `Clone::clone` has `None` for `Self`,
1619 /// while `<Vec<T> as Clone>::clone` has `Some(Vec<T>)` for `Self`,
1620 /// even though they both have the same two-segment `Clone::clone` `Path`.
1621 Resolved(Option<&'hir Ty<'hir>>, &'hir Path<'hir>),
1622
1623 /// Type-related paths (e.g., `<T>::default` or `<T>::Output`).
1624 /// Will be resolved by type-checking to an associated item.
1625 ///
1626 /// UFCS source paths can desugar into this, with `Vec::new` turning into
1627 /// `<Vec>::new`, and `T::X::Y::method` into `<<<T>::X>::Y>::method`,
1628 /// the `X` and `Y` nodes each being a `TyKind::Path(QPath::TypeRelative(..))`.
1629 TypeRelative(&'hir Ty<'hir>, &'hir PathSegment<'hir>),
1630
1631 /// Reference to a `#[lang = "foo"]` item.
1632 LangItem(LangItem, Span),
1633 }
1634
1635 impl<'hir> QPath<'hir> {
1636 /// Returns the span of this `QPath`.
1637 pub fn span(&self) -> Span {
1638 match *self {
1639 QPath::Resolved(_, path) => path.span,
1640 QPath::TypeRelative(_, ps) => ps.ident.span,
1641 QPath::LangItem(_, span) => span,
1642 }
1643 }
1644
1645 /// Returns the span of the qself of this `QPath`. For example, `()` in
1646 /// `<() as Trait>::method`.
1647 pub fn qself_span(&self) -> Span {
1648 match *self {
1649 QPath::Resolved(_, path) => path.span,
1650 QPath::TypeRelative(qself, _) => qself.span,
1651 QPath::LangItem(_, span) => span,
1652 }
1653 }
1654
1655 /// Returns the span of the last segment of this `QPath`. For example, `method` in
1656 /// `<() as Trait>::method`.
1657 pub fn last_segment_span(&self) -> Span {
1658 match *self {
1659 QPath::Resolved(_, path) => path.segments.last().unwrap().ident.span,
1660 QPath::TypeRelative(_, segment) => segment.ident.span,
1661 QPath::LangItem(_, span) => span,
1662 }
1663 }
1664 }
1665
1666 /// Hints at the original code for a let statement.
1667 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1668 pub enum LocalSource {
1669 /// A `match _ { .. }`.
1670 Normal,
1671 /// A desugared `for _ in _ { .. }` loop.
1672 ForLoopDesugar,
1673 /// When lowering async functions, we create locals within the `async move` so that
1674 /// all parameters are dropped after the future is polled.
1675 ///
1676 /// ```ignore (pseudo-Rust)
1677 /// async fn foo(<pattern> @ x: Type) {
1678 /// async move {
1679 /// let <pattern> = x;
1680 /// }
1681 /// }
1682 /// ```
1683 AsyncFn,
1684 /// A desugared `<expr>.await`.
1685 AwaitDesugar,
1686 /// A desugared `expr = expr`, where the LHS is a tuple, struct or array.
1687 /// The span is that of the `=` sign.
1688 AssignDesugar(Span),
1689 }
1690
1691 /// Hints at the original code for a `match _ { .. }`.
1692 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)]
1693 #[derive(HashStable_Generic)]
1694 pub enum MatchSource {
1695 /// A `match _ { .. }`.
1696 Normal,
1697 /// An `if _ { .. }` (optionally with `else { .. }`).
1698 IfDesugar { contains_else_clause: bool },
1699 /// An `if let _ = _ { .. }` (optionally with `else { .. }`).
1700 IfLetDesugar { contains_else_clause: bool },
1701 /// A `while _ { .. }` (which was desugared to a `loop { match _ { .. } }`).
1702 WhileDesugar,
1703 /// A `while let _ = _ { .. }` (which was desugared to a
1704 /// `loop { match _ { .. } }`).
1705 WhileLetDesugar,
1706 /// A desugared `for _ in _ { .. }` loop.
1707 ForLoopDesugar,
1708 /// A desugared `?` operator.
1709 TryDesugar,
1710 /// A desugared `<expr>.await`.
1711 AwaitDesugar,
1712 }
1713
1714 impl MatchSource {
1715 pub fn name(self) -> &'static str {
1716 use MatchSource::*;
1717 match self {
1718 Normal => "match",
1719 IfDesugar { .. } | IfLetDesugar { .. } => "if",
1720 WhileDesugar | WhileLetDesugar => "while",
1721 ForLoopDesugar => "for",
1722 TryDesugar => "?",
1723 AwaitDesugar => ".await",
1724 }
1725 }
1726 }
1727
1728 /// The loop type that yielded an `ExprKind::Loop`.
1729 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
1730 pub enum LoopSource {
1731 /// A `loop { .. }` loop.
1732 Loop,
1733 /// A `while _ { .. }` loop.
1734 While,
1735 /// A `while let _ = _ { .. }` loop.
1736 WhileLet,
1737 /// A `for _ in _ { .. }` loop.
1738 ForLoop,
1739 }
1740
1741 impl LoopSource {
1742 pub fn name(self) -> &'static str {
1743 match self {
1744 LoopSource::Loop => "loop",
1745 LoopSource::While | LoopSource::WhileLet => "while",
1746 LoopSource::ForLoop => "for",
1747 }
1748 }
1749 }
1750
1751 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1752 pub enum LoopIdError {
1753 OutsideLoopScope,
1754 UnlabeledCfInWhileCondition,
1755 UnresolvedLabel,
1756 }
1757
1758 impl fmt::Display for LoopIdError {
1759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1760 f.write_str(match self {
1761 LoopIdError::OutsideLoopScope => "not inside loop scope",
1762 LoopIdError::UnlabeledCfInWhileCondition => {
1763 "unlabeled control flow (break or continue) in while condition"
1764 }
1765 LoopIdError::UnresolvedLabel => "label not found",
1766 })
1767 }
1768 }
1769
1770 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
1771 pub struct Destination {
1772 // This is `Some(_)` iff there is an explicit user-specified `label
1773 pub label: Option<Label>,
1774
1775 // These errors are caught and then reported during the diagnostics pass in
1776 // librustc_passes/loops.rs
1777 pub target_id: Result<HirId, LoopIdError>,
1778 }
1779
1780 /// The yield kind that caused an `ExprKind::Yield`.
1781 #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)]
1782 pub enum YieldSource {
1783 /// An `<expr>.await`.
1784 Await { expr: Option<HirId> },
1785 /// A plain `yield`.
1786 Yield,
1787 }
1788
1789 impl YieldSource {
1790 pub fn is_await(&self) -> bool {
1791 match self {
1792 YieldSource::Await { .. } => true,
1793 YieldSource::Yield => false,
1794 }
1795 }
1796 }
1797
1798 impl fmt::Display for YieldSource {
1799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800 f.write_str(match self {
1801 YieldSource::Await { .. } => "`await`",
1802 YieldSource::Yield => "`yield`",
1803 })
1804 }
1805 }
1806
1807 impl From<GeneratorKind> for YieldSource {
1808 fn from(kind: GeneratorKind) -> Self {
1809 match kind {
1810 // Guess based on the kind of the current generator.
1811 GeneratorKind::Gen => Self::Yield,
1812 GeneratorKind::Async(_) => Self::Await { expr: None },
1813 }
1814 }
1815 }
1816
1817 // N.B., if you change this, you'll probably want to change the corresponding
1818 // type structure in middle/ty.rs as well.
1819 #[derive(Debug, HashStable_Generic)]
1820 pub struct MutTy<'hir> {
1821 pub ty: &'hir Ty<'hir>,
1822 pub mutbl: Mutability,
1823 }
1824
1825 /// Represents a function's signature in a trait declaration,
1826 /// trait implementation, or a free function.
1827 #[derive(Debug, HashStable_Generic)]
1828 pub struct FnSig<'hir> {
1829 pub header: FnHeader,
1830 pub decl: &'hir FnDecl<'hir>,
1831 pub span: Span,
1832 }
1833
1834 // The bodies for items are stored "out of line", in a separate
1835 // hashmap in the `Crate`. Here we just record the node-id of the item
1836 // so it can fetched later.
1837 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1838 pub struct TraitItemId {
1839 pub hir_id: HirId,
1840 }
1841
1842 /// Represents an item declaration within a trait declaration,
1843 /// possibly including a default implementation. A trait item is
1844 /// either required (meaning it doesn't have an implementation, just a
1845 /// signature) or provided (meaning it has a default implementation).
1846 #[derive(Debug)]
1847 pub struct TraitItem<'hir> {
1848 pub ident: Ident,
1849 pub hir_id: HirId,
1850 pub attrs: &'hir [Attribute],
1851 pub generics: Generics<'hir>,
1852 pub kind: TraitItemKind<'hir>,
1853 pub span: Span,
1854 }
1855
1856 /// Represents a trait method's body (or just argument names).
1857 #[derive(Encodable, Debug, HashStable_Generic)]
1858 pub enum TraitFn<'hir> {
1859 /// No default body in the trait, just a signature.
1860 Required(&'hir [Ident]),
1861
1862 /// Both signature and body are provided in the trait.
1863 Provided(BodyId),
1864 }
1865
1866 /// Represents a trait method or associated constant or type
1867 #[derive(Debug, HashStable_Generic)]
1868 pub enum TraitItemKind<'hir> {
1869 /// An associated constant with an optional value (otherwise `impl`s must contain a value).
1870 Const(&'hir Ty<'hir>, Option<BodyId>),
1871 /// An associated function with an optional body.
1872 Fn(FnSig<'hir>, TraitFn<'hir>),
1873 /// An associated type with (possibly empty) bounds and optional concrete
1874 /// type.
1875 Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>),
1876 }
1877
1878 // The bodies for items are stored "out of line", in a separate
1879 // hashmap in the `Crate`. Here we just record the node-id of the item
1880 // so it can fetched later.
1881 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Debug)]
1882 pub struct ImplItemId {
1883 pub hir_id: HirId,
1884 }
1885
1886 /// Represents anything within an `impl` block.
1887 #[derive(Debug)]
1888 pub struct ImplItem<'hir> {
1889 pub ident: Ident,
1890 pub hir_id: HirId,
1891 pub vis: Visibility<'hir>,
1892 pub defaultness: Defaultness,
1893 pub attrs: &'hir [Attribute],
1894 pub generics: Generics<'hir>,
1895 pub kind: ImplItemKind<'hir>,
1896 pub span: Span,
1897 }
1898
1899 /// Represents various kinds of content within an `impl`.
1900 #[derive(Debug, HashStable_Generic)]
1901 pub enum ImplItemKind<'hir> {
1902 /// An associated constant of the given type, set to the constant result
1903 /// of the expression.
1904 Const(&'hir Ty<'hir>, BodyId),
1905 /// An associated function implementation with the given signature and body.
1906 Fn(FnSig<'hir>, BodyId),
1907 /// An associated type.
1908 TyAlias(&'hir Ty<'hir>),
1909 }
1910
1911 impl ImplItemKind<'_> {
1912 pub fn namespace(&self) -> Namespace {
1913 match self {
1914 ImplItemKind::TyAlias(..) => Namespace::TypeNS,
1915 ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS,
1916 }
1917 }
1918 }
1919
1920 // The name of the associated type for `Fn` return types.
1921 pub const FN_OUTPUT_NAME: Symbol = sym::Output;
1922
1923 /// Bind a type to an associated type (i.e., `A = Foo`).
1924 ///
1925 /// Bindings like `A: Debug` are represented as a special type `A =
1926 /// $::Debug` that is understood by the astconv code.
1927 ///
1928 /// FIXME(alexreg): why have a separate type for the binding case,
1929 /// wouldn't it be better to make the `ty` field an enum like the
1930 /// following?
1931 ///
1932 /// ```
1933 /// enum TypeBindingKind {
1934 /// Equals(...),
1935 /// Binding(...),
1936 /// }
1937 /// ```
1938 #[derive(Debug, HashStable_Generic)]
1939 pub struct TypeBinding<'hir> {
1940 pub hir_id: HirId,
1941 #[stable_hasher(project(name))]
1942 pub ident: Ident,
1943 pub kind: TypeBindingKind<'hir>,
1944 pub span: Span,
1945 }
1946
1947 // Represents the two kinds of type bindings.
1948 #[derive(Debug, HashStable_Generic)]
1949 pub enum TypeBindingKind<'hir> {
1950 /// E.g., `Foo<Bar: Send>`.
1951 Constraint { bounds: &'hir [GenericBound<'hir>] },
1952 /// E.g., `Foo<Bar = ()>`.
1953 Equality { ty: &'hir Ty<'hir> },
1954 }
1955
1956 impl TypeBinding<'_> {
1957 pub fn ty(&self) -> &Ty<'_> {
1958 match self.kind {
1959 TypeBindingKind::Equality { ref ty } => ty,
1960 _ => panic!("expected equality type binding for parenthesized generic args"),
1961 }
1962 }
1963 }
1964
1965 #[derive(Debug)]
1966 pub struct Ty<'hir> {
1967 pub hir_id: HirId,
1968 pub kind: TyKind<'hir>,
1969 pub span: Span,
1970 }
1971
1972 /// Not represented directly in the AST; referred to by name through a `ty_path`.
1973 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1974 #[derive(HashStable_Generic)]
1975 pub enum PrimTy {
1976 Int(IntTy),
1977 Uint(UintTy),
1978 Float(FloatTy),
1979 Str,
1980 Bool,
1981 Char,
1982 }
1983
1984 impl PrimTy {
1985 pub fn name_str(self) -> &'static str {
1986 match self {
1987 PrimTy::Int(i) => i.name_str(),
1988 PrimTy::Uint(u) => u.name_str(),
1989 PrimTy::Float(f) => f.name_str(),
1990 PrimTy::Str => "str",
1991 PrimTy::Bool => "bool",
1992 PrimTy::Char => "char",
1993 }
1994 }
1995
1996 pub fn name(self) -> Symbol {
1997 match self {
1998 PrimTy::Int(i) => i.name(),
1999 PrimTy::Uint(u) => u.name(),
2000 PrimTy::Float(f) => f.name(),
2001 PrimTy::Str => sym::str,
2002 PrimTy::Bool => sym::bool,
2003 PrimTy::Char => sym::char,
2004 }
2005 }
2006 }
2007
2008 #[derive(Debug, HashStable_Generic)]
2009 pub struct BareFnTy<'hir> {
2010 pub unsafety: Unsafety,
2011 pub abi: Abi,
2012 pub generic_params: &'hir [GenericParam<'hir>],
2013 pub decl: &'hir FnDecl<'hir>,
2014 pub param_names: &'hir [Ident],
2015 }
2016
2017 #[derive(Debug, HashStable_Generic)]
2018 pub struct OpaqueTy<'hir> {
2019 pub generics: Generics<'hir>,
2020 pub bounds: GenericBounds<'hir>,
2021 pub impl_trait_fn: Option<DefId>,
2022 pub origin: OpaqueTyOrigin,
2023 }
2024
2025 /// From whence the opaque type came.
2026 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2027 pub enum OpaqueTyOrigin {
2028 /// `-> impl Trait`
2029 FnReturn,
2030 /// `async fn`
2031 AsyncFn,
2032 /// `let _: impl Trait = ...`
2033 Binding,
2034 /// Impl trait in type aliases, consts, statics, bounds.
2035 Misc,
2036 }
2037
2038 /// The various kinds of types recognized by the compiler.
2039 #[derive(Debug, HashStable_Generic)]
2040 pub enum TyKind<'hir> {
2041 /// A variable length slice (i.e., `[T]`).
2042 Slice(&'hir Ty<'hir>),
2043 /// A fixed length array (i.e., `[T; n]`).
2044 Array(&'hir Ty<'hir>, AnonConst),
2045 /// A raw pointer (i.e., `*const T` or `*mut T`).
2046 Ptr(MutTy<'hir>),
2047 /// A reference (i.e., `&'a T` or `&'a mut T`).
2048 Rptr(Lifetime, MutTy<'hir>),
2049 /// A bare function (e.g., `fn(usize) -> bool`).
2050 BareFn(&'hir BareFnTy<'hir>),
2051 /// The never type (`!`).
2052 Never,
2053 /// A tuple (`(A, B, C, D, ...)`).
2054 Tup(&'hir [Ty<'hir>]),
2055 /// A path to a type definition (`module::module::...::Type`), or an
2056 /// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
2057 ///
2058 /// Type parameters may be stored in each `PathSegment`.
2059 Path(QPath<'hir>),
2060 /// A opaque type definition itself. This is currently only used for the
2061 /// `opaque type Foo: Trait` item that `impl Trait` in desugars to.
2062 ///
2063 /// The generic argument list contains the lifetimes (and in the future
2064 /// possibly parameters) that are actually bound on the `impl Trait`.
2065 OpaqueDef(ItemId, &'hir [GenericArg<'hir>]),
2066 /// A trait object type `Bound1 + Bound2 + Bound3`
2067 /// where `Bound` is a trait or a lifetime.
2068 TraitObject(&'hir [PolyTraitRef<'hir>], Lifetime),
2069 /// Unused for now.
2070 Typeof(AnonConst),
2071 /// `TyKind::Infer` means the type should be inferred instead of it having been
2072 /// specified. This can appear anywhere in a type.
2073 Infer,
2074 /// Placeholder for a type that has failed to be defined.
2075 Err,
2076 }
2077
2078 #[derive(Debug, HashStable_Generic)]
2079 pub enum InlineAsmOperand<'hir> {
2080 In {
2081 reg: InlineAsmRegOrRegClass,
2082 expr: Expr<'hir>,
2083 },
2084 Out {
2085 reg: InlineAsmRegOrRegClass,
2086 late: bool,
2087 expr: Option<Expr<'hir>>,
2088 },
2089 InOut {
2090 reg: InlineAsmRegOrRegClass,
2091 late: bool,
2092 expr: Expr<'hir>,
2093 },
2094 SplitInOut {
2095 reg: InlineAsmRegOrRegClass,
2096 late: bool,
2097 in_expr: Expr<'hir>,
2098 out_expr: Option<Expr<'hir>>,
2099 },
2100 Const {
2101 expr: Expr<'hir>,
2102 },
2103 Sym {
2104 expr: Expr<'hir>,
2105 },
2106 }
2107
2108 impl<'hir> InlineAsmOperand<'hir> {
2109 pub fn reg(&self) -> Option<InlineAsmRegOrRegClass> {
2110 match *self {
2111 Self::In { reg, .. }
2112 | Self::Out { reg, .. }
2113 | Self::InOut { reg, .. }
2114 | Self::SplitInOut { reg, .. } => Some(reg),
2115 Self::Const { .. } | Self::Sym { .. } => None,
2116 }
2117 }
2118 }
2119
2120 #[derive(Debug, HashStable_Generic)]
2121 pub struct InlineAsm<'hir> {
2122 pub template: &'hir [InlineAsmTemplatePiece],
2123 pub operands: &'hir [InlineAsmOperand<'hir>],
2124 pub options: InlineAsmOptions,
2125 pub line_spans: &'hir [Span],
2126 }
2127
2128 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2129 pub struct LlvmInlineAsmOutput {
2130 pub constraint: Symbol,
2131 pub is_rw: bool,
2132 pub is_indirect: bool,
2133 pub span: Span,
2134 }
2135
2136 // NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
2137 // it needs to be `Clone` and `Decodable` and use plain `Vec<T>` instead of
2138 // arena-allocated slice.
2139 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, PartialEq)]
2140 pub struct LlvmInlineAsmInner {
2141 pub asm: Symbol,
2142 pub asm_str_style: StrStyle,
2143 pub outputs: Vec<LlvmInlineAsmOutput>,
2144 pub inputs: Vec<Symbol>,
2145 pub clobbers: Vec<Symbol>,
2146 pub volatile: bool,
2147 pub alignstack: bool,
2148 pub dialect: LlvmAsmDialect,
2149 }
2150
2151 #[derive(Debug, HashStable_Generic)]
2152 pub struct LlvmInlineAsm<'hir> {
2153 pub inner: LlvmInlineAsmInner,
2154 pub outputs_exprs: &'hir [Expr<'hir>],
2155 pub inputs_exprs: &'hir [Expr<'hir>],
2156 }
2157
2158 /// Represents a parameter in a function header.
2159 #[derive(Debug, HashStable_Generic)]
2160 pub struct Param<'hir> {
2161 pub attrs: &'hir [Attribute],
2162 pub hir_id: HirId,
2163 pub pat: &'hir Pat<'hir>,
2164 pub ty_span: Span,
2165 pub span: Span,
2166 }
2167
2168 /// Represents the header (not the body) of a function declaration.
2169 #[derive(Debug, HashStable_Generic)]
2170 pub struct FnDecl<'hir> {
2171 /// The types of the function's parameters.
2172 ///
2173 /// Additional argument data is stored in the function's [body](Body::params).
2174 pub inputs: &'hir [Ty<'hir>],
2175 pub output: FnRetTy<'hir>,
2176 pub c_variadic: bool,
2177 /// Does the function have an implicit self?
2178 pub implicit_self: ImplicitSelfKind,
2179 }
2180
2181 /// Represents what type of implicit self a function has, if any.
2182 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2183 pub enum ImplicitSelfKind {
2184 /// Represents a `fn x(self);`.
2185 Imm,
2186 /// Represents a `fn x(mut self);`.
2187 Mut,
2188 /// Represents a `fn x(&self);`.
2189 ImmRef,
2190 /// Represents a `fn x(&mut self);`.
2191 MutRef,
2192 /// Represents when a function does not have a self argument or
2193 /// when a function has a `self: X` argument.
2194 None,
2195 }
2196
2197 impl ImplicitSelfKind {
2198 /// Does this represent an implicit self?
2199 pub fn has_implicit_self(&self) -> bool {
2200 !matches!(*self, ImplicitSelfKind::None)
2201 }
2202 }
2203
2204 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Debug)]
2205 #[derive(HashStable_Generic)]
2206 pub enum IsAsync {
2207 Async,
2208 NotAsync,
2209 }
2210
2211 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
2212 pub enum Defaultness {
2213 Default { has_value: bool },
2214 Final,
2215 }
2216
2217 impl Defaultness {
2218 pub fn has_value(&self) -> bool {
2219 match *self {
2220 Defaultness::Default { has_value } => has_value,
2221 Defaultness::Final => true,
2222 }
2223 }
2224
2225 pub fn is_final(&self) -> bool {
2226 *self == Defaultness::Final
2227 }
2228
2229 pub fn is_default(&self) -> bool {
2230 matches!(*self, Defaultness::Default { .. })
2231 }
2232 }
2233
2234 #[derive(Debug, HashStable_Generic)]
2235 pub enum FnRetTy<'hir> {
2236 /// Return type is not specified.
2237 ///
2238 /// Functions default to `()` and
2239 /// closures default to inference. Span points to where return
2240 /// type would be inserted.
2241 DefaultReturn(Span),
2242 /// Everything else.
2243 Return(&'hir Ty<'hir>),
2244 }
2245
2246 impl FnRetTy<'_> {
2247 pub fn span(&self) -> Span {
2248 match *self {
2249 Self::DefaultReturn(span) => span,
2250 Self::Return(ref ty) => ty.span,
2251 }
2252 }
2253 }
2254
2255 #[derive(Encodable, Debug)]
2256 pub struct Mod<'hir> {
2257 /// A span from the first token past `{` to the last token until `}`.
2258 /// For `mod foo;`, the inner span ranges from the first token
2259 /// to the last token in the external file.
2260 pub inner: Span,
2261 pub item_ids: &'hir [ItemId],
2262 }
2263
2264 #[derive(Debug, HashStable_Generic)]
2265 pub struct ForeignMod<'hir> {
2266 pub abi: Abi,
2267 pub items: &'hir [ForeignItem<'hir>],
2268 }
2269
2270 #[derive(Encodable, Debug, HashStable_Generic)]
2271 pub struct GlobalAsm {
2272 pub asm: Symbol,
2273 }
2274
2275 #[derive(Debug, HashStable_Generic)]
2276 pub struct EnumDef<'hir> {
2277 pub variants: &'hir [Variant<'hir>],
2278 }
2279
2280 #[derive(Debug, HashStable_Generic)]
2281 pub struct Variant<'hir> {
2282 /// Name of the variant.
2283 #[stable_hasher(project(name))]
2284 pub ident: Ident,
2285 /// Attributes of the variant.
2286 pub attrs: &'hir [Attribute],
2287 /// Id of the variant (not the constructor, see `VariantData::ctor_hir_id()`).
2288 pub id: HirId,
2289 /// Fields and constructor id of the variant.
2290 pub data: VariantData<'hir>,
2291 /// Explicit discriminant (e.g., `Foo = 1`).
2292 pub disr_expr: Option<AnonConst>,
2293 /// Span
2294 pub span: Span,
2295 }
2296
2297 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2298 pub enum UseKind {
2299 /// One import, e.g., `use foo::bar` or `use foo::bar as baz`.
2300 /// Also produced for each element of a list `use`, e.g.
2301 /// `use foo::{a, b}` lowers to `use foo::a; use foo::b;`.
2302 Single,
2303
2304 /// Glob import, e.g., `use foo::*`.
2305 Glob,
2306
2307 /// Degenerate list import, e.g., `use foo::{a, b}` produces
2308 /// an additional `use foo::{}` for performing checks such as
2309 /// unstable feature gating. May be removed in the future.
2310 ListStem,
2311 }
2312
2313 /// References to traits in impls.
2314 ///
2315 /// `resolve` maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2316 /// that the `ref_id` is for. Note that `ref_id`'s value is not the `HirId` of the
2317 /// trait being referred to but just a unique `HirId` that serves as a key
2318 /// within the resolution map.
2319 #[derive(Debug, HashStable_Generic)]
2320 pub struct TraitRef<'hir> {
2321 pub path: &'hir Path<'hir>,
2322 // Don't hash the `ref_id`. It is tracked via the thing it is used to access.
2323 #[stable_hasher(ignore)]
2324 pub hir_ref_id: HirId,
2325 }
2326
2327 impl TraitRef<'_> {
2328 /// Gets the `DefId` of the referenced trait. It _must_ actually be a trait or trait alias.
2329 pub fn trait_def_id(&self) -> Option<DefId> {
2330 match self.path.res {
2331 Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2332 Res::Err => None,
2333 _ => unreachable!(),
2334 }
2335 }
2336 }
2337
2338 #[derive(Debug, HashStable_Generic)]
2339 pub struct PolyTraitRef<'hir> {
2340 /// The `'a` in `for<'a> Foo<&'a T>`.
2341 pub bound_generic_params: &'hir [GenericParam<'hir>],
2342
2343 /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>`.
2344 pub trait_ref: TraitRef<'hir>,
2345
2346 pub span: Span,
2347 }
2348
2349 pub type Visibility<'hir> = Spanned<VisibilityKind<'hir>>;
2350
2351 #[derive(Debug)]
2352 pub enum VisibilityKind<'hir> {
2353 Public,
2354 Crate(CrateSugar),
2355 Restricted { path: &'hir Path<'hir>, hir_id: HirId },
2356 Inherited,
2357 }
2358
2359 impl VisibilityKind<'_> {
2360 pub fn is_pub(&self) -> bool {
2361 matches!(*self, VisibilityKind::Public)
2362 }
2363
2364 pub fn is_pub_restricted(&self) -> bool {
2365 match *self {
2366 VisibilityKind::Public | VisibilityKind::Inherited => false,
2367 VisibilityKind::Crate(..) | VisibilityKind::Restricted { .. } => true,
2368 }
2369 }
2370 }
2371
2372 #[derive(Debug, HashStable_Generic)]
2373 pub struct StructField<'hir> {
2374 pub span: Span,
2375 #[stable_hasher(project(name))]
2376 pub ident: Ident,
2377 pub vis: Visibility<'hir>,
2378 pub hir_id: HirId,
2379 pub ty: &'hir Ty<'hir>,
2380 pub attrs: &'hir [Attribute],
2381 }
2382
2383 impl StructField<'_> {
2384 // Still necessary in couple of places
2385 pub fn is_positional(&self) -> bool {
2386 let first = self.ident.as_str().as_bytes()[0];
2387 first >= b'0' && first <= b'9'
2388 }
2389 }
2390
2391 /// Fields and constructor IDs of enum variants and structs.
2392 #[derive(Debug, HashStable_Generic)]
2393 pub enum VariantData<'hir> {
2394 /// A struct variant.
2395 ///
2396 /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2397 Struct(&'hir [StructField<'hir>], /* recovered */ bool),
2398 /// A tuple variant.
2399 ///
2400 /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2401 Tuple(&'hir [StructField<'hir>], HirId),
2402 /// A unit variant.
2403 ///
2404 /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2405 Unit(HirId),
2406 }
2407
2408 impl VariantData<'hir> {
2409 /// Return the fields of this variant.
2410 pub fn fields(&self) -> &'hir [StructField<'hir>] {
2411 match *self {
2412 VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, ..) => fields,
2413 _ => &[],
2414 }
2415 }
2416
2417 /// Return the `HirId` of this variant's constructor, if it has one.
2418 pub fn ctor_hir_id(&self) -> Option<HirId> {
2419 match *self {
2420 VariantData::Struct(_, _) => None,
2421 VariantData::Tuple(_, hir_id) | VariantData::Unit(hir_id) => Some(hir_id),
2422 }
2423 }
2424 }
2425
2426 // The bodies for items are stored "out of line", in a separate
2427 // hashmap in the `Crate`. Here we just record the node-id of the item
2428 // so it can fetched later.
2429 #[derive(Copy, Clone, Encodable, Debug)]
2430 pub struct ItemId {
2431 pub id: HirId,
2432 }
2433
2434 /// An item
2435 ///
2436 /// The name might be a dummy name in case of anonymous items
2437 #[derive(Debug)]
2438 pub struct Item<'hir> {
2439 pub ident: Ident,
2440 pub hir_id: HirId,
2441 pub attrs: &'hir [Attribute],
2442 pub kind: ItemKind<'hir>,
2443 pub vis: Visibility<'hir>,
2444 pub span: Span,
2445 }
2446
2447 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2448 #[derive(Encodable, Decodable, HashStable_Generic)]
2449 pub enum Unsafety {
2450 Unsafe,
2451 Normal,
2452 }
2453
2454 impl Unsafety {
2455 pub fn prefix_str(&self) -> &'static str {
2456 match self {
2457 Self::Unsafe => "unsafe ",
2458 Self::Normal => "",
2459 }
2460 }
2461 }
2462
2463 impl fmt::Display for Unsafety {
2464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2465 f.write_str(match *self {
2466 Self::Unsafe => "unsafe",
2467 Self::Normal => "normal",
2468 })
2469 }
2470 }
2471
2472 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
2473 #[derive(Encodable, Decodable, HashStable_Generic)]
2474 pub enum Constness {
2475 Const,
2476 NotConst,
2477 }
2478
2479 #[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)]
2480 pub struct FnHeader {
2481 pub unsafety: Unsafety,
2482 pub constness: Constness,
2483 pub asyncness: IsAsync,
2484 pub abi: Abi,
2485 }
2486
2487 impl FnHeader {
2488 pub fn is_const(&self) -> bool {
2489 matches!(&self.constness, Constness::Const)
2490 }
2491 }
2492
2493 #[derive(Debug, HashStable_Generic)]
2494 pub enum ItemKind<'hir> {
2495 /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2496 ///
2497 /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2498 ExternCrate(Option<Symbol>),
2499
2500 /// `use foo::bar::*;` or `use foo::bar::baz as quux;`
2501 ///
2502 /// or just
2503 ///
2504 /// `use foo::bar::baz;` (with `as baz` implicitly on the right).
2505 Use(&'hir Path<'hir>, UseKind),
2506
2507 /// A `static` item.
2508 Static(&'hir Ty<'hir>, Mutability, BodyId),
2509 /// A `const` item.
2510 Const(&'hir Ty<'hir>, BodyId),
2511 /// A function declaration.
2512 Fn(FnSig<'hir>, Generics<'hir>, BodyId),
2513 /// A module.
2514 Mod(Mod<'hir>),
2515 /// An external module, e.g. `extern { .. }`.
2516 ForeignMod(ForeignMod<'hir>),
2517 /// Module-level inline assembly (from `global_asm!`).
2518 GlobalAsm(&'hir GlobalAsm),
2519 /// A type alias, e.g., `type Foo = Bar<u8>`.
2520 TyAlias(&'hir Ty<'hir>, Generics<'hir>),
2521 /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`.
2522 OpaqueTy(OpaqueTy<'hir>),
2523 /// An enum definition, e.g., `enum Foo<A, B> {C<A>, D<B>}`.
2524 Enum(EnumDef<'hir>, Generics<'hir>),
2525 /// A struct definition, e.g., `struct Foo<A> {x: A}`.
2526 Struct(VariantData<'hir>, Generics<'hir>),
2527 /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
2528 Union(VariantData<'hir>, Generics<'hir>),
2529 /// A trait definition.
2530 Trait(IsAuto, Unsafety, Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
2531 /// A trait alias.
2532 TraitAlias(Generics<'hir>, GenericBounds<'hir>),
2533
2534 /// An implementation, e.g., `impl<A> Trait for Foo { .. }`.
2535 Impl {
2536 unsafety: Unsafety,
2537 polarity: ImplPolarity,
2538 defaultness: Defaultness,
2539 // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata
2540 // decoding as `Span`s cannot be decoded when a `Session` is not available.
2541 defaultness_span: Option<Span>,
2542 constness: Constness,
2543 generics: Generics<'hir>,
2544
2545 /// The trait being implemented, if any.
2546 of_trait: Option<TraitRef<'hir>>,
2547
2548 self_ty: &'hir Ty<'hir>,
2549 items: &'hir [ImplItemRef<'hir>],
2550 },
2551 }
2552
2553 impl ItemKind<'_> {
2554 pub fn generics(&self) -> Option<&Generics<'_>> {
2555 Some(match *self {
2556 ItemKind::Fn(_, ref generics, _)
2557 | ItemKind::TyAlias(_, ref generics)
2558 | ItemKind::OpaqueTy(OpaqueTy { ref generics, impl_trait_fn: None, .. })
2559 | ItemKind::Enum(_, ref generics)
2560 | ItemKind::Struct(_, ref generics)
2561 | ItemKind::Union(_, ref generics)
2562 | ItemKind::Trait(_, _, ref generics, _, _)
2563 | ItemKind::Impl { ref generics, .. } => generics,
2564 _ => return None,
2565 })
2566 }
2567 }
2568
2569 /// A reference from an trait to one of its associated items. This
2570 /// contains the item's id, naturally, but also the item's name and
2571 /// some other high-level details (like whether it is an associated
2572 /// type or method, and whether it is public). This allows other
2573 /// passes to find the impl they want without loading the ID (which
2574 /// means fewer edges in the incremental compilation graph).
2575 #[derive(Encodable, Debug, HashStable_Generic)]
2576 pub struct TraitItemRef {
2577 pub id: TraitItemId,
2578 #[stable_hasher(project(name))]
2579 pub ident: Ident,
2580 pub kind: AssocItemKind,
2581 pub span: Span,
2582 pub defaultness: Defaultness,
2583 }
2584
2585 /// A reference from an impl to one of its associated items. This
2586 /// contains the item's ID, naturally, but also the item's name and
2587 /// some other high-level details (like whether it is an associated
2588 /// type or method, and whether it is public). This allows other
2589 /// passes to find the impl they want without loading the ID (which
2590 /// means fewer edges in the incremental compilation graph).
2591 #[derive(Debug, HashStable_Generic)]
2592 pub struct ImplItemRef<'hir> {
2593 pub id: ImplItemId,
2594 #[stable_hasher(project(name))]
2595 pub ident: Ident,
2596 pub kind: AssocItemKind,
2597 pub span: Span,
2598 pub vis: Visibility<'hir>,
2599 pub defaultness: Defaultness,
2600 }
2601
2602 #[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)]
2603 pub enum AssocItemKind {
2604 Const,
2605 Fn { has_self: bool },
2606 Type,
2607 }
2608
2609 #[derive(Debug, HashStable_Generic)]
2610 pub struct ForeignItem<'hir> {
2611 #[stable_hasher(project(name))]
2612 pub ident: Ident,
2613 pub attrs: &'hir [Attribute],
2614 pub kind: ForeignItemKind<'hir>,
2615 pub hir_id: HirId,
2616 pub span: Span,
2617 pub vis: Visibility<'hir>,
2618 }
2619
2620 /// An item within an `extern` block.
2621 #[derive(Debug, HashStable_Generic)]
2622 pub enum ForeignItemKind<'hir> {
2623 /// A foreign function.
2624 Fn(&'hir FnDecl<'hir>, &'hir [Ident], Generics<'hir>),
2625 /// A foreign static item (`static ext: u8`).
2626 Static(&'hir Ty<'hir>, Mutability),
2627 /// A foreign type.
2628 Type,
2629 }
2630
2631 /// A variable captured by a closure.
2632 #[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)]
2633 pub struct Upvar {
2634 // First span where it is accessed (there can be multiple).
2635 pub span: Span,
2636 }
2637
2638 // The TraitCandidate's import_ids is empty if the trait is defined in the same module, and
2639 // has length > 0 if the trait is found through an chain of imports, starting with the
2640 // import/use statement in the scope where the trait is used.
2641 #[derive(Encodable, Decodable, Clone, Debug)]
2642 pub struct TraitCandidate {
2643 pub def_id: DefId,
2644 pub import_ids: SmallVec<[LocalDefId; 1]>,
2645 }
2646
2647 #[derive(Copy, Clone, Debug, HashStable_Generic)]
2648 pub enum Node<'hir> {
2649 Param(&'hir Param<'hir>),
2650 Item(&'hir Item<'hir>),
2651 ForeignItem(&'hir ForeignItem<'hir>),
2652 TraitItem(&'hir TraitItem<'hir>),
2653 ImplItem(&'hir ImplItem<'hir>),
2654 Variant(&'hir Variant<'hir>),
2655 Field(&'hir StructField<'hir>),
2656 AnonConst(&'hir AnonConst),
2657 Expr(&'hir Expr<'hir>),
2658 Stmt(&'hir Stmt<'hir>),
2659 PathSegment(&'hir PathSegment<'hir>),
2660 Ty(&'hir Ty<'hir>),
2661 TraitRef(&'hir TraitRef<'hir>),
2662 Binding(&'hir Pat<'hir>),
2663 Pat(&'hir Pat<'hir>),
2664 Arm(&'hir Arm<'hir>),
2665 Block(&'hir Block<'hir>),
2666 Local(&'hir Local<'hir>),
2667 MacroDef(&'hir MacroDef<'hir>),
2668
2669 /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
2670 /// with synthesized constructors.
2671 Ctor(&'hir VariantData<'hir>),
2672
2673 Lifetime(&'hir Lifetime),
2674 GenericParam(&'hir GenericParam<'hir>),
2675 Visibility(&'hir Visibility<'hir>),
2676
2677 Crate(&'hir CrateItem<'hir>),
2678 }
2679
2680 impl<'hir> Node<'hir> {
2681 pub fn ident(&self) -> Option<Ident> {
2682 match self {
2683 Node::TraitItem(TraitItem { ident, .. })
2684 | Node::ImplItem(ImplItem { ident, .. })
2685 | Node::ForeignItem(ForeignItem { ident, .. })
2686 | Node::Field(StructField { ident, .. })
2687 | Node::Variant(Variant { ident, .. })
2688 | Node::MacroDef(MacroDef { ident, .. })
2689 | Node::Item(Item { ident, .. }) => Some(*ident),
2690 _ => None,
2691 }
2692 }
2693
2694 pub fn fn_decl(&self) -> Option<&FnDecl<'hir>> {
2695 match self {
2696 Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
2697 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
2698 | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl),
2699 Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
2700 Some(fn_decl)
2701 }
2702 _ => None,
2703 }
2704 }
2705
2706 pub fn body_id(&self) -> Option<BodyId> {
2707 match self {
2708 Node::TraitItem(TraitItem {
2709 kind: TraitItemKind::Fn(_, TraitFn::Provided(body_id)),
2710 ..
2711 })
2712 | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })
2713 | Node::Item(Item { kind: ItemKind::Fn(.., body_id), .. }) => Some(*body_id),
2714 _ => None,
2715 }
2716 }
2717
2718 pub fn generics(&self) -> Option<&'hir Generics<'hir>> {
2719 match self {
2720 Node::TraitItem(TraitItem { generics, .. })
2721 | Node::ImplItem(ImplItem { generics, .. }) => Some(generics),
2722 Node::Item(item) => item.kind.generics(),
2723 _ => None,
2724 }
2725 }
2726
2727 pub fn hir_id(&self) -> Option<HirId> {
2728 match self {
2729 Node::Item(Item { hir_id, .. })
2730 | Node::ForeignItem(ForeignItem { hir_id, .. })
2731 | Node::TraitItem(TraitItem { hir_id, .. })
2732 | Node::ImplItem(ImplItem { hir_id, .. })
2733 | Node::Field(StructField { hir_id, .. })
2734 | Node::AnonConst(AnonConst { hir_id, .. })
2735 | Node::Expr(Expr { hir_id, .. })
2736 | Node::Stmt(Stmt { hir_id, .. })
2737 | Node::Ty(Ty { hir_id, .. })
2738 | Node::Binding(Pat { hir_id, .. })
2739 | Node::Pat(Pat { hir_id, .. })
2740 | Node::Arm(Arm { hir_id, .. })
2741 | Node::Block(Block { hir_id, .. })
2742 | Node::Local(Local { hir_id, .. })
2743 | Node::MacroDef(MacroDef { hir_id, .. })
2744 | Node::Lifetime(Lifetime { hir_id, .. })
2745 | Node::Param(Param { hir_id, .. })
2746 | Node::GenericParam(GenericParam { hir_id, .. }) => Some(*hir_id),
2747 Node::TraitRef(TraitRef { hir_ref_id, .. }) => Some(*hir_ref_id),
2748 Node::PathSegment(PathSegment { hir_id, .. }) => *hir_id,
2749 Node::Variant(Variant { id, .. }) => Some(*id),
2750 Node::Ctor(variant) => variant.ctor_hir_id(),
2751 Node::Crate(_) | Node::Visibility(_) => None,
2752 }
2753 }
2754 }