]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/ast.rs
Auto merge of #104688 - flip1995:clippyup, r=Manishearth,flip1995
[rust.git] / compiler / rustc_ast / src / ast.rs
1 //! The Rust abstract syntax tree module.
2 //!
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
7 //!
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
20
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
24
25 use crate::ptr::P;
26 use crate::token::{self, CommentKind, Delimiter};
27 use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_data_structures::stack::ensure_sufficient_stack;
30 use rustc_data_structures::sync::Lrc;
31 use rustc_macros::HashStable_Generic;
32 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
33 use rustc_span::source_map::{respan, Spanned};
34 use rustc_span::symbol::{kw, sym, Ident, Symbol};
35 use rustc_span::{Span, DUMMY_SP};
36 use std::convert::TryFrom;
37 use std::fmt;
38 use std::mem;
39 use thin_vec::{thin_vec, ThinVec};
40
41 /// A "Label" is an identifier of some point in sources,
42 /// e.g. in the following code:
43 ///
44 /// ```rust
45 /// 'outer: loop {
46 ///     break 'outer;
47 /// }
48 /// ```
49 ///
50 /// `'outer` is a label.
51 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
52 pub struct Label {
53     pub ident: Ident,
54 }
55
56 impl fmt::Debug for Label {
57     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58         write!(f, "label({:?})", self.ident)
59     }
60 }
61
62 /// A "Lifetime" is an annotation of the scope in which variable
63 /// can be used, e.g. `'a` in `&'a i32`.
64 #[derive(Clone, Encodable, Decodable, Copy, PartialEq, Eq)]
65 pub struct Lifetime {
66     pub id: NodeId,
67     pub ident: Ident,
68 }
69
70 impl fmt::Debug for Lifetime {
71     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72         write!(f, "lifetime({}: {})", self.id, self)
73     }
74 }
75
76 impl fmt::Display for Lifetime {
77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         write!(f, "{}", self.ident.name)
79     }
80 }
81
82 /// A "Path" is essentially Rust's notion of a name.
83 ///
84 /// It's represented as a sequence of identifiers,
85 /// along with a bunch of supporting information.
86 ///
87 /// E.g., `std::cmp::PartialEq`.
88 #[derive(Clone, Encodable, Decodable, Debug)]
89 pub struct Path {
90     pub span: Span,
91     /// The segments in the path: the things separated by `::`.
92     /// Global paths begin with `kw::PathRoot`.
93     pub segments: ThinVec<PathSegment>,
94     pub tokens: Option<LazyAttrTokenStream>,
95 }
96
97 impl PartialEq<Symbol> for Path {
98     #[inline]
99     fn eq(&self, symbol: &Symbol) -> bool {
100         self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
101     }
102 }
103
104 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
105     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
106         self.segments.len().hash_stable(hcx, hasher);
107         for segment in &self.segments {
108             segment.ident.hash_stable(hcx, hasher);
109         }
110     }
111 }
112
113 impl Path {
114     // Convert a span and an identifier to the corresponding
115     // one-segment path.
116     pub fn from_ident(ident: Ident) -> Path {
117         Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
118     }
119
120     pub fn is_global(&self) -> bool {
121         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
122     }
123 }
124
125 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
126 ///
127 /// E.g., `std`, `String` or `Box<T>`.
128 #[derive(Clone, Encodable, Decodable, Debug)]
129 pub struct PathSegment {
130     /// The identifier portion of this path segment.
131     pub ident: Ident,
132
133     pub id: NodeId,
134
135     /// Type/lifetime parameters attached to this path. They come in
136     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
137     /// `None` means that no parameter list is supplied (`Path`),
138     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
139     /// but it can be empty (`Path<>`).
140     /// `P` is used as a size optimization for the common case with no parameters.
141     pub args: Option<P<GenericArgs>>,
142 }
143
144 impl PathSegment {
145     pub fn from_ident(ident: Ident) -> Self {
146         PathSegment { ident, id: DUMMY_NODE_ID, args: None }
147     }
148
149     pub fn path_root(span: Span) -> Self {
150         PathSegment::from_ident(Ident::new(kw::PathRoot, span))
151     }
152
153     pub fn span(&self) -> Span {
154         match &self.args {
155             Some(args) => self.ident.span.to(args.span()),
156             None => self.ident.span,
157         }
158     }
159 }
160
161 /// The arguments of a path segment.
162 ///
163 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
164 #[derive(Clone, Encodable, Decodable, Debug)]
165 pub enum GenericArgs {
166     /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
167     AngleBracketed(AngleBracketedArgs),
168     /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
169     Parenthesized(ParenthesizedArgs),
170 }
171
172 impl GenericArgs {
173     pub fn is_angle_bracketed(&self) -> bool {
174         matches!(self, AngleBracketed(..))
175     }
176
177     pub fn span(&self) -> Span {
178         match self {
179             AngleBracketed(data) => data.span,
180             Parenthesized(data) => data.span,
181         }
182     }
183 }
184
185 /// Concrete argument in the sequence of generic args.
186 #[derive(Clone, Encodable, Decodable, Debug)]
187 pub enum GenericArg {
188     /// `'a` in `Foo<'a>`
189     Lifetime(Lifetime),
190     /// `Bar` in `Foo<Bar>`
191     Type(P<Ty>),
192     /// `1` in `Foo<1>`
193     Const(AnonConst),
194 }
195
196 impl GenericArg {
197     pub fn span(&self) -> Span {
198         match self {
199             GenericArg::Lifetime(lt) => lt.ident.span,
200             GenericArg::Type(ty) => ty.span,
201             GenericArg::Const(ct) => ct.value.span,
202         }
203     }
204 }
205
206 /// A path like `Foo<'a, T>`.
207 #[derive(Clone, Encodable, Decodable, Debug, Default)]
208 pub struct AngleBracketedArgs {
209     /// The overall span.
210     pub span: Span,
211     /// The comma separated parts in the `<...>`.
212     pub args: Vec<AngleBracketedArg>,
213 }
214
215 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
216 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
217 #[derive(Clone, Encodable, Decodable, Debug)]
218 pub enum AngleBracketedArg {
219     /// Argument for a generic parameter.
220     Arg(GenericArg),
221     /// Constraint for an associated item.
222     Constraint(AssocConstraint),
223 }
224
225 impl AngleBracketedArg {
226     pub fn span(&self) -> Span {
227         match self {
228             AngleBracketedArg::Arg(arg) => arg.span(),
229             AngleBracketedArg::Constraint(constraint) => constraint.span,
230         }
231     }
232 }
233
234 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
235     fn into(self) -> Option<P<GenericArgs>> {
236         Some(P(GenericArgs::AngleBracketed(self)))
237     }
238 }
239
240 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
241     fn into(self) -> Option<P<GenericArgs>> {
242         Some(P(GenericArgs::Parenthesized(self)))
243     }
244 }
245
246 /// A path like `Foo(A, B) -> C`.
247 #[derive(Clone, Encodable, Decodable, Debug)]
248 pub struct ParenthesizedArgs {
249     /// ```text
250     /// Foo(A, B) -> C
251     /// ^^^^^^^^^^^^^^
252     /// ```
253     pub span: Span,
254
255     /// `(A, B)`
256     pub inputs: Vec<P<Ty>>,
257
258     /// ```text
259     /// Foo(A, B) -> C
260     ///    ^^^^^^
261     /// ```
262     pub inputs_span: Span,
263
264     /// `C`
265     pub output: FnRetTy,
266 }
267
268 impl ParenthesizedArgs {
269     pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
270         let args = self
271             .inputs
272             .iter()
273             .cloned()
274             .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
275             .collect();
276         AngleBracketedArgs { span: self.inputs_span, args }
277     }
278 }
279
280 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
281
282 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
283 ///
284 /// Negative bounds should also be handled here.
285 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
286 pub enum TraitBoundModifier {
287     /// No modifiers
288     None,
289
290     /// `?Trait`
291     Maybe,
292
293     /// `~const Trait`
294     MaybeConst,
295
296     /// `~const ?Trait`
297     //
298     // This parses but will be rejected during AST validation.
299     MaybeConstMaybe,
300 }
301
302 /// The AST represents all type param bounds as types.
303 /// `typeck::collect::compute_bounds` matches these against
304 /// the "special" built-in traits (see `middle::lang_items`) and
305 /// detects `Copy`, `Send` and `Sync`.
306 #[derive(Clone, Encodable, Decodable, Debug)]
307 pub enum GenericBound {
308     Trait(PolyTraitRef, TraitBoundModifier),
309     Outlives(Lifetime),
310 }
311
312 impl GenericBound {
313     pub fn span(&self) -> Span {
314         match self {
315             GenericBound::Trait(t, ..) => t.span,
316             GenericBound::Outlives(l) => l.ident.span,
317         }
318     }
319 }
320
321 pub type GenericBounds = Vec<GenericBound>;
322
323 /// Specifies the enforced ordering for generic parameters. In the future,
324 /// if we wanted to relax this order, we could override `PartialEq` and
325 /// `PartialOrd`, to allow the kinds to be unordered.
326 #[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
327 pub enum ParamKindOrd {
328     Lifetime,
329     TypeOrConst,
330 }
331
332 impl fmt::Display for ParamKindOrd {
333     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334         match self {
335             ParamKindOrd::Lifetime => "lifetime".fmt(f),
336             ParamKindOrd::TypeOrConst => "type and const".fmt(f),
337         }
338     }
339 }
340
341 #[derive(Clone, Encodable, Decodable, Debug)]
342 pub enum GenericParamKind {
343     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
344     Lifetime,
345     Type {
346         default: Option<P<Ty>>,
347     },
348     Const {
349         ty: P<Ty>,
350         /// Span of the `const` keyword.
351         kw_span: Span,
352         /// Optional default value for the const generic param
353         default: Option<AnonConst>,
354     },
355 }
356
357 #[derive(Clone, Encodable, Decodable, Debug)]
358 pub struct GenericParam {
359     pub id: NodeId,
360     pub ident: Ident,
361     pub attrs: AttrVec,
362     pub bounds: GenericBounds,
363     pub is_placeholder: bool,
364     pub kind: GenericParamKind,
365     pub colon_span: Option<Span>,
366 }
367
368 impl GenericParam {
369     pub fn span(&self) -> Span {
370         match &self.kind {
371             GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => {
372                 self.ident.span
373             }
374             GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span),
375             GenericParamKind::Const { kw_span, default: Some(default), .. } => {
376                 kw_span.to(default.value.span)
377             }
378             GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span),
379         }
380     }
381 }
382
383 /// Represents lifetime, type and const parameters attached to a declaration of
384 /// a function, enum, trait, etc.
385 #[derive(Clone, Encodable, Decodable, Debug)]
386 pub struct Generics {
387     pub params: Vec<GenericParam>,
388     pub where_clause: WhereClause,
389     pub span: Span,
390 }
391
392 impl Default for Generics {
393     /// Creates an instance of `Generics`.
394     fn default() -> Generics {
395         Generics { params: Vec::new(), where_clause: Default::default(), span: DUMMY_SP }
396     }
397 }
398
399 /// A where-clause in a definition.
400 #[derive(Clone, Encodable, Decodable, Debug)]
401 pub struct WhereClause {
402     /// `true` if we ate a `where` token: this can happen
403     /// if we parsed no predicates (e.g. `struct Foo where {}`).
404     /// This allows us to pretty-print accurately.
405     pub has_where_token: bool,
406     pub predicates: Vec<WherePredicate>,
407     pub span: Span,
408 }
409
410 impl Default for WhereClause {
411     fn default() -> WhereClause {
412         WhereClause { has_where_token: false, predicates: Vec::new(), span: DUMMY_SP }
413     }
414 }
415
416 /// A single predicate in a where-clause.
417 #[derive(Clone, Encodable, Decodable, Debug)]
418 pub enum WherePredicate {
419     /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
420     BoundPredicate(WhereBoundPredicate),
421     /// A lifetime predicate (e.g., `'a: 'b + 'c`).
422     RegionPredicate(WhereRegionPredicate),
423     /// An equality predicate (unsupported).
424     EqPredicate(WhereEqPredicate),
425 }
426
427 impl WherePredicate {
428     pub fn span(&self) -> Span {
429         match self {
430             WherePredicate::BoundPredicate(p) => p.span,
431             WherePredicate::RegionPredicate(p) => p.span,
432             WherePredicate::EqPredicate(p) => p.span,
433         }
434     }
435 }
436
437 /// A type bound.
438 ///
439 /// E.g., `for<'c> Foo: Send + Clone + 'c`.
440 #[derive(Clone, Encodable, Decodable, Debug)]
441 pub struct WhereBoundPredicate {
442     pub span: Span,
443     /// Any generics from a `for` binding.
444     pub bound_generic_params: Vec<GenericParam>,
445     /// The type being bounded.
446     pub bounded_ty: P<Ty>,
447     /// Trait and lifetime bounds (`Clone + Send + 'static`).
448     pub bounds: GenericBounds,
449 }
450
451 /// A lifetime predicate.
452 ///
453 /// E.g., `'a: 'b + 'c`.
454 #[derive(Clone, Encodable, Decodable, Debug)]
455 pub struct WhereRegionPredicate {
456     pub span: Span,
457     pub lifetime: Lifetime,
458     pub bounds: GenericBounds,
459 }
460
461 /// An equality predicate (unsupported).
462 ///
463 /// E.g., `T = int`.
464 #[derive(Clone, Encodable, Decodable, Debug)]
465 pub struct WhereEqPredicate {
466     pub span: Span,
467     pub lhs_ty: P<Ty>,
468     pub rhs_ty: P<Ty>,
469 }
470
471 #[derive(Clone, Encodable, Decodable, Debug)]
472 pub struct Crate {
473     pub attrs: AttrVec,
474     pub items: Vec<P<Item>>,
475     pub spans: ModSpans,
476     /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold
477     /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that.
478     pub id: NodeId,
479     pub is_placeholder: bool,
480 }
481
482 /// Possible values inside of compile-time attribute lists.
483 ///
484 /// E.g., the '..' in `#[name(..)]`.
485 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
486 pub enum NestedMetaItem {
487     /// A full MetaItem, for recursive meta items.
488     MetaItem(MetaItem),
489     /// A literal.
490     ///
491     /// E.g., `"foo"`, `64`, `true`.
492     Literal(Lit),
493 }
494
495 /// A spanned compile-time attribute item.
496 ///
497 /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
498 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
499 pub struct MetaItem {
500     pub path: Path,
501     pub kind: MetaItemKind,
502     pub span: Span,
503 }
504
505 /// A compile-time attribute item.
506 ///
507 /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
508 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
509 pub enum MetaItemKind {
510     /// Word meta item.
511     ///
512     /// E.g., `test` as in `#[test]`.
513     Word,
514     /// List meta item.
515     ///
516     /// E.g., `derive(..)` as in `#[derive(..)]`.
517     List(Vec<NestedMetaItem>),
518     /// Name value meta item.
519     ///
520     /// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
521     NameValue(Lit),
522 }
523
524 /// A block (`{ .. }`).
525 ///
526 /// E.g., `{ .. }` as in `fn foo() { .. }`.
527 #[derive(Clone, Encodable, Decodable, Debug)]
528 pub struct Block {
529     /// The statements in the block.
530     pub stmts: Vec<Stmt>,
531     pub id: NodeId,
532     /// Distinguishes between `unsafe { ... }` and `{ ... }`.
533     pub rules: BlockCheckMode,
534     pub span: Span,
535     pub tokens: Option<LazyAttrTokenStream>,
536     /// The following *isn't* a parse error, but will cause multiple errors in following stages.
537     /// ```compile_fail
538     /// let x = {
539     ///     foo: var
540     /// };
541     /// ```
542     /// #34255
543     pub could_be_bare_literal: bool,
544 }
545
546 /// A match pattern.
547 ///
548 /// Patterns appear in match statements and some other contexts, such as `let` and `if let`.
549 #[derive(Clone, Encodable, Decodable, Debug)]
550 pub struct Pat {
551     pub id: NodeId,
552     pub kind: PatKind,
553     pub span: Span,
554     pub tokens: Option<LazyAttrTokenStream>,
555 }
556
557 impl Pat {
558     /// Attempt reparsing the pattern as a type.
559     /// This is intended for use by diagnostics.
560     pub fn to_ty(&self) -> Option<P<Ty>> {
561         let kind = match &self.kind {
562             // In a type expression `_` is an inference variable.
563             PatKind::Wild => TyKind::Infer,
564             // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
565             PatKind::Ident(BindingAnnotation::NONE, ident, None) => {
566                 TyKind::Path(None, Path::from_ident(*ident))
567             }
568             PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
569             PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
570             // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
571             PatKind::Ref(pat, mutbl) => {
572                 pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
573             }
574             // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
575             // when `P` can be reparsed as a type `T`.
576             PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
577             // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
578             // assuming `T0` to `Tn` are all syntactically valid as types.
579             PatKind::Tuple(pats) => {
580                 let mut tys = Vec::with_capacity(pats.len());
581                 // FIXME(#48994) - could just be collected into an Option<Vec>
582                 for pat in pats {
583                     tys.push(pat.to_ty()?);
584                 }
585                 TyKind::Tup(tys)
586             }
587             _ => return None,
588         };
589
590         Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
591     }
592
593     /// Walk top-down and call `it` in each place where a pattern occurs
594     /// starting with the root pattern `walk` is called on. If `it` returns
595     /// false then we will descend no further but siblings will be processed.
596     pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
597         if !it(self) {
598             return;
599         }
600
601         match &self.kind {
602             // Walk into the pattern associated with `Ident` (if any).
603             PatKind::Ident(_, _, Some(p)) => p.walk(it),
604
605             // Walk into each field of struct.
606             PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
607
608             // Sequence of patterns.
609             PatKind::TupleStruct(_, _, s)
610             | PatKind::Tuple(s)
611             | PatKind::Slice(s)
612             | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
613
614             // Trivial wrappers over inner patterns.
615             PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
616
617             // These patterns do not contain subpatterns, skip.
618             PatKind::Wild
619             | PatKind::Rest
620             | PatKind::Lit(_)
621             | PatKind::Range(..)
622             | PatKind::Ident(..)
623             | PatKind::Path(..)
624             | PatKind::MacCall(_) => {}
625         }
626     }
627
628     /// Is this a `..` pattern?
629     pub fn is_rest(&self) -> bool {
630         matches!(self.kind, PatKind::Rest)
631     }
632 }
633
634 /// A single field in a struct pattern.
635 ///
636 /// Patterns like the fields of `Foo { x, ref y, ref mut z }`
637 /// are treated the same as `x: x, y: ref y, z: ref mut z`,
638 /// except when `is_shorthand` is true.
639 #[derive(Clone, Encodable, Decodable, Debug)]
640 pub struct PatField {
641     /// The identifier for the field.
642     pub ident: Ident,
643     /// The pattern the field is destructured to.
644     pub pat: P<Pat>,
645     pub is_shorthand: bool,
646     pub attrs: AttrVec,
647     pub id: NodeId,
648     pub span: Span,
649     pub is_placeholder: bool,
650 }
651
652 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
653 #[derive(Encodable, Decodable, HashStable_Generic)]
654 pub enum ByRef {
655     Yes,
656     No,
657 }
658
659 impl From<bool> for ByRef {
660     fn from(b: bool) -> ByRef {
661         match b {
662             false => ByRef::No,
663             true => ByRef::Yes,
664         }
665     }
666 }
667
668 /// Explicit binding annotations given in the HIR for a binding. Note
669 /// that this is not the final binding *mode* that we infer after type
670 /// inference.
671 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
672 #[derive(Encodable, Decodable, HashStable_Generic)]
673 pub struct BindingAnnotation(pub ByRef, pub Mutability);
674
675 impl BindingAnnotation {
676     pub const NONE: Self = Self(ByRef::No, Mutability::Not);
677     pub const REF: Self = Self(ByRef::Yes, Mutability::Not);
678     pub const MUT: Self = Self(ByRef::No, Mutability::Mut);
679     pub const REF_MUT: Self = Self(ByRef::Yes, Mutability::Mut);
680
681     pub fn prefix_str(self) -> &'static str {
682         match self {
683             Self::NONE => "",
684             Self::REF => "ref ",
685             Self::MUT => "mut ",
686             Self::REF_MUT => "ref mut ",
687         }
688     }
689 }
690
691 #[derive(Clone, Encodable, Decodable, Debug)]
692 pub enum RangeEnd {
693     /// `..=` or `...`
694     Included(RangeSyntax),
695     /// `..`
696     Excluded,
697 }
698
699 #[derive(Clone, Encodable, Decodable, Debug)]
700 pub enum RangeSyntax {
701     /// `...`
702     DotDotDot,
703     /// `..=`
704     DotDotEq,
705 }
706
707 /// All the different flavors of pattern that Rust recognizes.
708 #[derive(Clone, Encodable, Decodable, Debug)]
709 pub enum PatKind {
710     /// Represents a wildcard pattern (`_`).
711     Wild,
712
713     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
714     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
715     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
716     /// during name resolution.
717     Ident(BindingAnnotation, Ident, Option<P<Pat>>),
718
719     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
720     /// The `bool` is `true` in the presence of a `..`.
721     Struct(Option<P<QSelf>>, Path, Vec<PatField>, /* recovered */ bool),
722
723     /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
724     TupleStruct(Option<P<QSelf>>, Path, Vec<P<Pat>>),
725
726     /// An or-pattern `A | B | C`.
727     /// Invariant: `pats.len() >= 2`.
728     Or(Vec<P<Pat>>),
729
730     /// A possibly qualified path pattern.
731     /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
732     /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
733     /// only legally refer to associated constants.
734     Path(Option<P<QSelf>>, Path),
735
736     /// A tuple pattern (`(a, b)`).
737     Tuple(Vec<P<Pat>>),
738
739     /// A `box` pattern.
740     Box(P<Pat>),
741
742     /// A reference pattern (e.g., `&mut (a, b)`).
743     Ref(P<Pat>, Mutability),
744
745     /// A literal.
746     Lit(P<Expr>),
747
748     /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
749     Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>),
750
751     /// A slice pattern `[a, b, c]`.
752     Slice(Vec<P<Pat>>),
753
754     /// A rest pattern `..`.
755     ///
756     /// Syntactically it is valid anywhere.
757     ///
758     /// Semantically however, it only has meaning immediately inside:
759     /// - a slice pattern: `[a, .., b]`,
760     /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
761     /// - a tuple pattern: `(a, .., b)`,
762     /// - a tuple struct/variant pattern: `$path(a, .., b)`.
763     ///
764     /// In all of these cases, an additional restriction applies,
765     /// only one rest pattern may occur in the pattern sequences.
766     Rest,
767
768     /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
769     Paren(P<Pat>),
770
771     /// A macro pattern; pre-expansion.
772     MacCall(P<MacCall>),
773 }
774
775 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)]
776 #[derive(HashStable_Generic, Encodable, Decodable)]
777 pub enum Mutability {
778     Mut,
779     Not,
780 }
781
782 impl Mutability {
783     pub fn invert(self) -> Self {
784         match self {
785             Mutability::Mut => Mutability::Not,
786             Mutability::Not => Mutability::Mut,
787         }
788     }
789
790     pub fn prefix_str(&self) -> &'static str {
791         match self {
792             Mutability::Mut => "mut ",
793             Mutability::Not => "",
794         }
795     }
796 }
797
798 /// The kind of borrow in an `AddrOf` expression,
799 /// e.g., `&place` or `&raw const place`.
800 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
801 #[derive(Encodable, Decodable, HashStable_Generic)]
802 pub enum BorrowKind {
803     /// A normal borrow, `&$expr` or `&mut $expr`.
804     /// The resulting type is either `&'a T` or `&'a mut T`
805     /// where `T = typeof($expr)` and `'a` is some lifetime.
806     Ref,
807     /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
808     /// The resulting type is either `*const T` or `*mut T`
809     /// where `T = typeof($expr)`.
810     Raw,
811 }
812
813 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
814 pub enum BinOpKind {
815     /// The `+` operator (addition)
816     Add,
817     /// The `-` operator (subtraction)
818     Sub,
819     /// The `*` operator (multiplication)
820     Mul,
821     /// The `/` operator (division)
822     Div,
823     /// The `%` operator (modulus)
824     Rem,
825     /// The `&&` operator (logical and)
826     And,
827     /// The `||` operator (logical or)
828     Or,
829     /// The `^` operator (bitwise xor)
830     BitXor,
831     /// The `&` operator (bitwise and)
832     BitAnd,
833     /// The `|` operator (bitwise or)
834     BitOr,
835     /// The `<<` operator (shift left)
836     Shl,
837     /// The `>>` operator (shift right)
838     Shr,
839     /// The `==` operator (equality)
840     Eq,
841     /// The `<` operator (less than)
842     Lt,
843     /// The `<=` operator (less than or equal to)
844     Le,
845     /// The `!=` operator (not equal to)
846     Ne,
847     /// The `>=` operator (greater than or equal to)
848     Ge,
849     /// The `>` operator (greater than)
850     Gt,
851 }
852
853 impl BinOpKind {
854     pub fn to_string(&self) -> &'static str {
855         use BinOpKind::*;
856         match *self {
857             Add => "+",
858             Sub => "-",
859             Mul => "*",
860             Div => "/",
861             Rem => "%",
862             And => "&&",
863             Or => "||",
864             BitXor => "^",
865             BitAnd => "&",
866             BitOr => "|",
867             Shl => "<<",
868             Shr => ">>",
869             Eq => "==",
870             Lt => "<",
871             Le => "<=",
872             Ne => "!=",
873             Ge => ">=",
874             Gt => ">",
875         }
876     }
877     pub fn lazy(&self) -> bool {
878         matches!(self, BinOpKind::And | BinOpKind::Or)
879     }
880
881     pub fn is_comparison(&self) -> bool {
882         use BinOpKind::*;
883         // Note for developers: please keep this as is;
884         // we want compilation to fail if another variant is added.
885         match *self {
886             Eq | Lt | Le | Ne | Gt | Ge => true,
887             And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
888         }
889     }
890 }
891
892 pub type BinOp = Spanned<BinOpKind>;
893
894 /// Unary operator.
895 ///
896 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
897 #[derive(Clone, Encodable, Decodable, Debug, Copy)]
898 pub enum UnOp {
899     /// The `*` operator for dereferencing
900     Deref,
901     /// The `!` operator for logical inversion
902     Not,
903     /// The `-` operator for negation
904     Neg,
905 }
906
907 impl UnOp {
908     pub fn to_string(op: UnOp) -> &'static str {
909         match op {
910             UnOp::Deref => "*",
911             UnOp::Not => "!",
912             UnOp::Neg => "-",
913         }
914     }
915 }
916
917 /// A statement
918 #[derive(Clone, Encodable, Decodable, Debug)]
919 pub struct Stmt {
920     pub id: NodeId,
921     pub kind: StmtKind,
922     pub span: Span,
923 }
924
925 impl Stmt {
926     pub fn has_trailing_semicolon(&self) -> bool {
927         match &self.kind {
928             StmtKind::Semi(_) => true,
929             StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon),
930             _ => false,
931         }
932     }
933
934     /// Converts a parsed `Stmt` to a `Stmt` with
935     /// a trailing semicolon.
936     ///
937     /// This only modifies the parsed AST struct, not the attached
938     /// `LazyAttrTokenStream`. The parser is responsible for calling
939     /// `ToAttrTokenStream::add_trailing_semi` when there is actually
940     /// a semicolon in the tokenstream.
941     pub fn add_trailing_semicolon(mut self) -> Self {
942         self.kind = match self.kind {
943             StmtKind::Expr(expr) => StmtKind::Semi(expr),
944             StmtKind::MacCall(mac) => {
945                 StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| {
946                     MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens }
947                 }))
948             }
949             kind => kind,
950         };
951
952         self
953     }
954
955     pub fn is_item(&self) -> bool {
956         matches!(self.kind, StmtKind::Item(_))
957     }
958
959     pub fn is_expr(&self) -> bool {
960         matches!(self.kind, StmtKind::Expr(_))
961     }
962 }
963
964 #[derive(Clone, Encodable, Decodable, Debug)]
965 pub enum StmtKind {
966     /// A local (let) binding.
967     Local(P<Local>),
968     /// An item definition.
969     Item(P<Item>),
970     /// Expr without trailing semi-colon.
971     Expr(P<Expr>),
972     /// Expr with a trailing semi-colon.
973     Semi(P<Expr>),
974     /// Just a trailing semi-colon.
975     Empty,
976     /// Macro.
977     MacCall(P<MacCallStmt>),
978 }
979
980 #[derive(Clone, Encodable, Decodable, Debug)]
981 pub struct MacCallStmt {
982     pub mac: P<MacCall>,
983     pub style: MacStmtStyle,
984     pub attrs: AttrVec,
985     pub tokens: Option<LazyAttrTokenStream>,
986 }
987
988 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
989 pub enum MacStmtStyle {
990     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
991     /// `foo!(...);`, `foo![...];`).
992     Semicolon,
993     /// The macro statement had braces (e.g., `foo! { ... }`).
994     Braces,
995     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
996     /// `foo!(...)`). All of these will end up being converted into macro
997     /// expressions.
998     NoBraces,
999 }
1000
1001 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
1002 #[derive(Clone, Encodable, Decodable, Debug)]
1003 pub struct Local {
1004     pub id: NodeId,
1005     pub pat: P<Pat>,
1006     pub ty: Option<P<Ty>>,
1007     pub kind: LocalKind,
1008     pub span: Span,
1009     pub attrs: AttrVec,
1010     pub tokens: Option<LazyAttrTokenStream>,
1011 }
1012
1013 #[derive(Clone, Encodable, Decodable, Debug)]
1014 pub enum LocalKind {
1015     /// Local declaration.
1016     /// Example: `let x;`
1017     Decl,
1018     /// Local declaration with an initializer.
1019     /// Example: `let x = y;`
1020     Init(P<Expr>),
1021     /// Local declaration with an initializer and an `else` clause.
1022     /// Example: `let Some(x) = y else { return };`
1023     InitElse(P<Expr>, P<Block>),
1024 }
1025
1026 impl LocalKind {
1027     pub fn init(&self) -> Option<&Expr> {
1028         match self {
1029             Self::Decl => None,
1030             Self::Init(i) | Self::InitElse(i, _) => Some(i),
1031         }
1032     }
1033
1034     pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> {
1035         match self {
1036             Self::Decl => None,
1037             Self::Init(init) => Some((init, None)),
1038             Self::InitElse(init, els) => Some((init, Some(els))),
1039         }
1040     }
1041 }
1042
1043 /// An arm of a 'match'.
1044 ///
1045 /// E.g., `0..=10 => { println!("match!") }` as in
1046 ///
1047 /// ```
1048 /// match 123 {
1049 ///     0..=10 => { println!("match!") },
1050 ///     _ => { println!("no match!") },
1051 /// }
1052 /// ```
1053 #[derive(Clone, Encodable, Decodable, Debug)]
1054 pub struct Arm {
1055     pub attrs: AttrVec,
1056     /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
1057     pub pat: P<Pat>,
1058     /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
1059     pub guard: Option<P<Expr>>,
1060     /// Match arm body.
1061     pub body: P<Expr>,
1062     pub span: Span,
1063     pub id: NodeId,
1064     pub is_placeholder: bool,
1065 }
1066
1067 /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`.
1068 #[derive(Clone, Encodable, Decodable, Debug)]
1069 pub struct ExprField {
1070     pub attrs: AttrVec,
1071     pub id: NodeId,
1072     pub span: Span,
1073     pub ident: Ident,
1074     pub expr: P<Expr>,
1075     pub is_shorthand: bool,
1076     pub is_placeholder: bool,
1077 }
1078
1079 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1080 pub enum BlockCheckMode {
1081     Default,
1082     Unsafe(UnsafeSource),
1083 }
1084
1085 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)]
1086 pub enum UnsafeSource {
1087     CompilerGenerated,
1088     UserProvided,
1089 }
1090
1091 /// A constant (expression) that's not an item or associated item,
1092 /// but needs its own `DefId` for type-checking, const-eval, etc.
1093 /// These are usually found nested inside types (e.g., array lengths)
1094 /// or expressions (e.g., repeat counts), and also used to define
1095 /// explicit discriminant values for enum variants.
1096 #[derive(Clone, Encodable, Decodable, Debug)]
1097 pub struct AnonConst {
1098     pub id: NodeId,
1099     pub value: P<Expr>,
1100 }
1101
1102 /// An expression.
1103 #[derive(Clone, Encodable, Decodable, Debug)]
1104 pub struct Expr {
1105     pub id: NodeId,
1106     pub kind: ExprKind,
1107     pub span: Span,
1108     pub attrs: AttrVec,
1109     pub tokens: Option<LazyAttrTokenStream>,
1110 }
1111
1112 impl Expr {
1113     /// Is this expr either `N`, or `{ N }`.
1114     ///
1115     /// If this is not the case, name resolution does not resolve `N` when using
1116     /// `min_const_generics` as more complex expressions are not supported.
1117     pub fn is_potential_trivial_const_param(&self) -> bool {
1118         let this = if let ExprKind::Block(block, None) = &self.kind
1119             && block.stmts.len() == 1
1120             && let StmtKind::Expr(expr) = &block.stmts[0].kind
1121         {
1122             expr
1123         } else {
1124             self
1125         };
1126
1127         if let ExprKind::Path(None, path) = &this.kind
1128             && path.segments.len() == 1
1129             && path.segments[0].args.is_none()
1130         {
1131             true
1132         } else {
1133             false
1134         }
1135     }
1136
1137     pub fn to_bound(&self) -> Option<GenericBound> {
1138         match &self.kind {
1139             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1140                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1141                 TraitBoundModifier::None,
1142             )),
1143             _ => None,
1144         }
1145     }
1146
1147     pub fn peel_parens(&self) -> &Expr {
1148         let mut expr = self;
1149         while let ExprKind::Paren(inner) = &expr.kind {
1150             expr = &inner;
1151         }
1152         expr
1153     }
1154
1155     /// Attempts to reparse as `Ty` (for diagnostic purposes).
1156     pub fn to_ty(&self) -> Option<P<Ty>> {
1157         let kind = match &self.kind {
1158             // Trivial conversions.
1159             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1160             ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()),
1161
1162             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1163
1164             ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => {
1165                 expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?
1166             }
1167
1168             ExprKind::Repeat(expr, expr_len) => {
1169                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1170             }
1171
1172             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1173
1174             ExprKind::Tup(exprs) => {
1175                 let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?;
1176                 TyKind::Tup(tys)
1177             }
1178
1179             // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1180             // then type of result is trait object.
1181             // Otherwise we don't assume the result type.
1182             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1183                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1184                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1185                 } else {
1186                     return None;
1187                 }
1188             }
1189
1190             ExprKind::Underscore => TyKind::Infer,
1191
1192             // This expression doesn't look like a type syntactically.
1193             _ => return None,
1194         };
1195
1196         Some(P(Ty { kind, id: self.id, span: self.span, tokens: None }))
1197     }
1198
1199     pub fn precedence(&self) -> ExprPrecedence {
1200         match self.kind {
1201             ExprKind::Box(_) => ExprPrecedence::Box,
1202             ExprKind::Array(_) => ExprPrecedence::Array,
1203             ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock,
1204             ExprKind::Call(..) => ExprPrecedence::Call,
1205             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1206             ExprKind::Tup(_) => ExprPrecedence::Tup,
1207             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1208             ExprKind::Unary(..) => ExprPrecedence::Unary,
1209             ExprKind::Lit(_) | ExprKind::IncludedBytes(..) => ExprPrecedence::Lit,
1210             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1211             ExprKind::Let(..) => ExprPrecedence::Let,
1212             ExprKind::If(..) => ExprPrecedence::If,
1213             ExprKind::While(..) => ExprPrecedence::While,
1214             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1215             ExprKind::Loop(..) => ExprPrecedence::Loop,
1216             ExprKind::Match(..) => ExprPrecedence::Match,
1217             ExprKind::Closure(..) => ExprPrecedence::Closure,
1218             ExprKind::Block(..) => ExprPrecedence::Block,
1219             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1220             ExprKind::Async(..) => ExprPrecedence::Async,
1221             ExprKind::Await(..) => ExprPrecedence::Await,
1222             ExprKind::Assign(..) => ExprPrecedence::Assign,
1223             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1224             ExprKind::Field(..) => ExprPrecedence::Field,
1225             ExprKind::Index(..) => ExprPrecedence::Index,
1226             ExprKind::Range(..) => ExprPrecedence::Range,
1227             ExprKind::Underscore => ExprPrecedence::Path,
1228             ExprKind::Path(..) => ExprPrecedence::Path,
1229             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1230             ExprKind::Break(..) => ExprPrecedence::Break,
1231             ExprKind::Continue(..) => ExprPrecedence::Continue,
1232             ExprKind::Ret(..) => ExprPrecedence::Ret,
1233             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1234             ExprKind::MacCall(..) => ExprPrecedence::Mac,
1235             ExprKind::Struct(..) => ExprPrecedence::Struct,
1236             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1237             ExprKind::Paren(..) => ExprPrecedence::Paren,
1238             ExprKind::Try(..) => ExprPrecedence::Try,
1239             ExprKind::Yield(..) => ExprPrecedence::Yield,
1240             ExprKind::Yeet(..) => ExprPrecedence::Yeet,
1241             ExprKind::Err => ExprPrecedence::Err,
1242         }
1243     }
1244
1245     pub fn take(&mut self) -> Self {
1246         mem::replace(
1247             self,
1248             Expr {
1249                 id: DUMMY_NODE_ID,
1250                 kind: ExprKind::Err,
1251                 span: DUMMY_SP,
1252                 attrs: AttrVec::new(),
1253                 tokens: None,
1254             },
1255         )
1256     }
1257
1258     // To a first-order approximation, is this a pattern
1259     pub fn is_approximately_pattern(&self) -> bool {
1260         match &self.peel_parens().kind {
1261             ExprKind::Box(_)
1262             | ExprKind::Array(_)
1263             | ExprKind::Call(_, _)
1264             | ExprKind::Tup(_)
1265             | ExprKind::Lit(_)
1266             | ExprKind::Range(_, _, _)
1267             | ExprKind::Underscore
1268             | ExprKind::Path(_, _)
1269             | ExprKind::Struct(_) => true,
1270             _ => false,
1271         }
1272     }
1273 }
1274
1275 #[derive(Clone, Encodable, Decodable, Debug)]
1276 pub struct Closure {
1277     pub binder: ClosureBinder,
1278     pub capture_clause: CaptureBy,
1279     pub asyncness: Async,
1280     pub movability: Movability,
1281     pub fn_decl: P<FnDecl>,
1282     pub body: P<Expr>,
1283     /// The span of the argument block `|...|`.
1284     pub fn_decl_span: Span,
1285 }
1286
1287 /// Limit types of a range (inclusive or exclusive)
1288 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)]
1289 pub enum RangeLimits {
1290     /// Inclusive at the beginning, exclusive at the end
1291     HalfOpen,
1292     /// Inclusive at the beginning and end
1293     Closed,
1294 }
1295
1296 /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1297 #[derive(Clone, Encodable, Decodable, Debug)]
1298 pub struct MethodCall {
1299     /// The method name and its generic arguments, e.g. `foo::<Bar, Baz>`.
1300     pub seg: PathSegment,
1301     /// The receiver, e.g. `x`.
1302     pub receiver: P<Expr>,
1303     /// The arguments, e.g. `a, b, c`.
1304     pub args: Vec<P<Expr>>,
1305     /// The span of the function, without the dot and receiver e.g. `foo::<Bar,
1306     /// Baz>(a, b, c)`.
1307     pub span: Span,
1308 }
1309
1310 #[derive(Clone, Encodable, Decodable, Debug)]
1311 pub enum StructRest {
1312     /// `..x`.
1313     Base(P<Expr>),
1314     /// `..`.
1315     Rest(Span),
1316     /// No trailing `..` or expression.
1317     None,
1318 }
1319
1320 #[derive(Clone, Encodable, Decodable, Debug)]
1321 pub struct StructExpr {
1322     pub qself: Option<P<QSelf>>,
1323     pub path: Path,
1324     pub fields: Vec<ExprField>,
1325     pub rest: StructRest,
1326 }
1327
1328 #[derive(Clone, Encodable, Decodable, Debug)]
1329 pub enum ExprKind {
1330     /// A `box x` expression.
1331     Box(P<Expr>),
1332     /// An array (`[a, b, c, d]`)
1333     Array(Vec<P<Expr>>),
1334     /// Allow anonymous constants from an inline `const` block
1335     ConstBlock(AnonConst),
1336     /// A function call
1337     ///
1338     /// The first field resolves to the function itself,
1339     /// and the second field is the list of arguments.
1340     /// This also represents calling the constructor of
1341     /// tuple-like ADTs such as tuple structs and enum variants.
1342     Call(P<Expr>, Vec<P<Expr>>),
1343     /// A method call (e.g. `x.foo::<Bar, Baz>(a, b, c)`).
1344     MethodCall(Box<MethodCall>),
1345     /// A tuple (e.g., `(a, b, c, d)`).
1346     Tup(Vec<P<Expr>>),
1347     /// A binary operation (e.g., `a + b`, `a * b`).
1348     Binary(BinOp, P<Expr>, P<Expr>),
1349     /// A unary operation (e.g., `!x`, `*x`).
1350     Unary(UnOp, P<Expr>),
1351     /// A literal (e.g., `1`, `"foo"`).
1352     Lit(token::Lit),
1353     /// A cast (e.g., `foo as f64`).
1354     Cast(P<Expr>, P<Ty>),
1355     /// A type ascription (e.g., `42: usize`).
1356     Type(P<Expr>, P<Ty>),
1357     /// A `let pat = expr` expression that is only semantically allowed in the condition
1358     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1359     ///
1360     /// `Span` represents the whole `let pat = expr` statement.
1361     Let(P<Pat>, P<Expr>, Span),
1362     /// An `if` block, with an optional `else` block.
1363     ///
1364     /// `if expr { block } else { expr }`
1365     If(P<Expr>, P<Block>, Option<P<Expr>>),
1366     /// A while loop, with an optional label.
1367     ///
1368     /// `'label: while expr { block }`
1369     While(P<Expr>, P<Block>, Option<Label>),
1370     /// A `for` loop, with an optional label.
1371     ///
1372     /// `'label: for pat in expr { block }`
1373     ///
1374     /// This is desugared to a combination of `loop` and `match` expressions.
1375     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1376     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1377     ///
1378     /// `'label: loop { block }`
1379     Loop(P<Block>, Option<Label>),
1380     /// A `match` block.
1381     Match(P<Expr>, Vec<Arm>),
1382     /// A closure (e.g., `move |a, b, c| a + b + c`).
1383     Closure(Box<Closure>),
1384     /// A block (`'label: { ... }`).
1385     Block(P<Block>, Option<Label>),
1386     /// An async block (`async move { ... }`).
1387     ///
1388     /// The `NodeId` is the `NodeId` for the closure that results from
1389     /// desugaring an async block, just like the NodeId field in the
1390     /// `Async::Yes` variant. This is necessary in order to create a def for the
1391     /// closure which can be used as a parent of any child defs. Defs
1392     /// created during lowering cannot be made the parent of any other
1393     /// preexisting defs.
1394     Async(CaptureBy, NodeId, P<Block>),
1395     /// An await expression (`my_future.await`).
1396     Await(P<Expr>),
1397
1398     /// A try block (`try { ... }`).
1399     TryBlock(P<Block>),
1400
1401     /// An assignment (`a = foo()`).
1402     /// The `Span` argument is the span of the `=` token.
1403     Assign(P<Expr>, P<Expr>, Span),
1404     /// An assignment with an operator.
1405     ///
1406     /// E.g., `a += 1`.
1407     AssignOp(BinOp, P<Expr>, P<Expr>),
1408     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1409     Field(P<Expr>, Ident),
1410     /// An indexing operation (e.g., `foo[2]`).
1411     Index(P<Expr>, P<Expr>),
1412     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment).
1413     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1414     /// An underscore, used in destructuring assignment to ignore a value.
1415     Underscore,
1416
1417     /// Variable reference, possibly containing `::` and/or type
1418     /// parameters (e.g., `foo::bar::<baz>`).
1419     ///
1420     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1421     Path(Option<P<QSelf>>, Path),
1422
1423     /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1424     AddrOf(BorrowKind, Mutability, P<Expr>),
1425     /// A `break`, with an optional label to break, and an optional expression.
1426     Break(Option<Label>, Option<P<Expr>>),
1427     /// A `continue`, with an optional label.
1428     Continue(Option<Label>),
1429     /// A `return`, with an optional value to be returned.
1430     Ret(Option<P<Expr>>),
1431
1432     /// Output of the `asm!()` macro.
1433     InlineAsm(P<InlineAsm>),
1434
1435     /// A macro invocation; pre-expansion.
1436     MacCall(P<MacCall>),
1437
1438     /// A struct literal expression.
1439     ///
1440     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`.
1441     Struct(P<StructExpr>),
1442
1443     /// An array literal constructed from one repeated element.
1444     ///
1445     /// E.g., `[1; 5]`. The expression is the element to be
1446     /// repeated; the constant is the number of times to repeat it.
1447     Repeat(P<Expr>, AnonConst),
1448
1449     /// No-op: used solely so we can pretty-print faithfully.
1450     Paren(P<Expr>),
1451
1452     /// A try expression (`expr?`).
1453     Try(P<Expr>),
1454
1455     /// A `yield`, with an optional value to be yielded.
1456     Yield(Option<P<Expr>>),
1457
1458     /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever),
1459     /// with an optional value to be returned.
1460     Yeet(Option<P<Expr>>),
1461
1462     /// Bytes included via `include_bytes!`
1463     /// Added for optimization purposes to avoid the need to escape
1464     /// large binary blobs - should always behave like [`ExprKind::Lit`]
1465     /// with a `ByteStr` literal.
1466     IncludedBytes(Lrc<[u8]>),
1467
1468     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1469     Err,
1470 }
1471
1472 /// The explicit `Self` type in a "qualified path". The actual
1473 /// path, including the trait and the associated item, is stored
1474 /// separately. `position` represents the index of the associated
1475 /// item qualified with this `Self` type.
1476 ///
1477 /// ```ignore (only-for-syntax-highlight)
1478 /// <Vec<T> as a::b::Trait>::AssociatedItem
1479 ///  ^~~~~     ~~~~~~~~~~~~~~^
1480 ///  ty        position = 3
1481 ///
1482 /// <Vec<T>>::AssociatedItem
1483 ///  ^~~~~    ^
1484 ///  ty       position = 0
1485 /// ```
1486 #[derive(Clone, Encodable, Decodable, Debug)]
1487 pub struct QSelf {
1488     pub ty: P<Ty>,
1489
1490     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1491     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1492     /// 0`, this is an empty span.
1493     pub path_span: Span,
1494     pub position: usize,
1495 }
1496
1497 /// A capture clause used in closures and `async` blocks.
1498 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
1499 pub enum CaptureBy {
1500     /// `move |x| y + x`.
1501     Value,
1502     /// `move` keyword was not specified.
1503     Ref,
1504 }
1505
1506 /// The movability of a generator / closure literal:
1507 /// whether a generator contains self-references, causing it to be `!Unpin`.
1508 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)]
1509 #[derive(HashStable_Generic)]
1510 pub enum Movability {
1511     /// May contain self-references, `!Unpin`.
1512     Static,
1513     /// Must not contain self-references, `Unpin`.
1514     Movable,
1515 }
1516
1517 /// Closure lifetime binder, `for<'a, 'b>` in `for<'a, 'b> |_: &'a (), _: &'b ()|`.
1518 #[derive(Clone, Encodable, Decodable, Debug)]
1519 pub enum ClosureBinder {
1520     /// The binder is not present, all closure lifetimes are inferred.
1521     NotPresent,
1522     /// The binder is present.
1523     For {
1524         /// Span of the whole `for<>` clause
1525         ///
1526         /// ```text
1527         /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1528         /// ^^^^^^^^^^^ -- this
1529         /// ```
1530         span: Span,
1531
1532         /// Lifetimes in the `for<>` closure
1533         ///
1534         /// ```text
1535         /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... }
1536         ///     ^^^^^^ -- this
1537         /// ```
1538         generic_params: P<[GenericParam]>,
1539     },
1540 }
1541
1542 /// Represents a macro invocation. The `path` indicates which macro
1543 /// is being invoked, and the `args` are arguments passed to it.
1544 #[derive(Clone, Encodable, Decodable, Debug)]
1545 pub struct MacCall {
1546     pub path: Path,
1547     pub args: P<DelimArgs>,
1548     pub prior_type_ascription: Option<(Span, bool)>,
1549 }
1550
1551 impl MacCall {
1552     pub fn span(&self) -> Span {
1553         self.path.span.to(self.args.dspan.entire())
1554     }
1555 }
1556
1557 /// Arguments passed to an attribute macro.
1558 #[derive(Clone, Encodable, Decodable, Debug)]
1559 pub enum AttrArgs {
1560     /// No arguments: `#[attr]`.
1561     Empty,
1562     /// Delimited arguments: `#[attr()/[]/{}]`.
1563     Delimited(DelimArgs),
1564     /// Arguments of a key-value attribute: `#[attr = "value"]`.
1565     Eq(
1566         /// Span of the `=` token.
1567         Span,
1568         /// The "value".
1569         AttrArgsEq,
1570     ),
1571 }
1572
1573 // The RHS of an `AttrArgs::Eq` starts out as an expression. Once macro
1574 // expansion is completed, all cases end up either as a literal, which is the
1575 // form used after lowering to HIR, or as an error.
1576 #[derive(Clone, Encodable, Decodable, Debug)]
1577 pub enum AttrArgsEq {
1578     Ast(P<Expr>),
1579     Hir(Lit),
1580 }
1581
1582 impl AttrArgs {
1583     pub fn span(&self) -> Option<Span> {
1584         match self {
1585             AttrArgs::Empty => None,
1586             AttrArgs::Delimited(args) => Some(args.dspan.entire()),
1587             AttrArgs::Eq(eq_span, AttrArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1588             AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1589                 unreachable!("in literal form when getting span: {:?}", lit);
1590             }
1591         }
1592     }
1593
1594     /// Tokens inside the delimiters or after `=`.
1595     /// Proc macros see these tokens, for example.
1596     pub fn inner_tokens(&self) -> TokenStream {
1597         match self {
1598             AttrArgs::Empty => TokenStream::default(),
1599             AttrArgs::Delimited(args) => args.tokens.clone(),
1600             AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => TokenStream::from_ast(expr),
1601             AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => {
1602                 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1603             }
1604         }
1605     }
1606 }
1607
1608 impl<CTX> HashStable<CTX> for AttrArgs
1609 where
1610     CTX: crate::HashStableContext,
1611 {
1612     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1613         mem::discriminant(self).hash_stable(ctx, hasher);
1614         match self {
1615             AttrArgs::Empty => {}
1616             AttrArgs::Delimited(args) => args.hash_stable(ctx, hasher),
1617             AttrArgs::Eq(_eq_span, AttrArgsEq::Ast(expr)) => {
1618                 unreachable!("hash_stable {:?}", expr);
1619             }
1620             AttrArgs::Eq(eq_span, AttrArgsEq::Hir(lit)) => {
1621                 eq_span.hash_stable(ctx, hasher);
1622                 lit.hash_stable(ctx, hasher);
1623             }
1624         }
1625     }
1626 }
1627
1628 /// Delimited arguments, as used in `#[attr()/[]/{}]` or `mac!()/[]/{}`.
1629 #[derive(Clone, Encodable, Decodable, Debug)]
1630 pub struct DelimArgs {
1631     pub dspan: DelimSpan,
1632     pub delim: MacDelimiter,
1633     pub tokens: TokenStream,
1634 }
1635
1636 impl DelimArgs {
1637     /// Whether a macro with these arguments needs a semicolon
1638     /// when used as a standalone item or statement.
1639     pub fn need_semicolon(&self) -> bool {
1640         !matches!(self, DelimArgs { delim: MacDelimiter::Brace, .. })
1641     }
1642 }
1643
1644 impl<CTX> HashStable<CTX> for DelimArgs
1645 where
1646     CTX: crate::HashStableContext,
1647 {
1648     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1649         let DelimArgs { dspan, delim, tokens } = self;
1650         dspan.hash_stable(ctx, hasher);
1651         delim.hash_stable(ctx, hasher);
1652         tokens.hash_stable(ctx, hasher);
1653     }
1654 }
1655
1656 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1657 pub enum MacDelimiter {
1658     Parenthesis,
1659     Bracket,
1660     Brace,
1661 }
1662
1663 impl MacDelimiter {
1664     pub fn to_token(self) -> Delimiter {
1665         match self {
1666             MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1667             MacDelimiter::Bracket => Delimiter::Bracket,
1668             MacDelimiter::Brace => Delimiter::Brace,
1669         }
1670     }
1671
1672     pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1673         match delim {
1674             Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1675             Delimiter::Bracket => Some(MacDelimiter::Bracket),
1676             Delimiter::Brace => Some(MacDelimiter::Brace),
1677             Delimiter::Invisible => None,
1678         }
1679     }
1680 }
1681
1682 /// Represents a macro definition.
1683 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1684 pub struct MacroDef {
1685     pub body: P<DelimArgs>,
1686     /// `true` if macro was defined with `macro_rules`.
1687     pub macro_rules: bool,
1688 }
1689
1690 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1691 #[derive(HashStable_Generic)]
1692 pub enum StrStyle {
1693     /// A regular string, like `"foo"`.
1694     Cooked,
1695     /// A raw string, like `r##"foo"##`.
1696     ///
1697     /// The value is the number of `#` symbols used.
1698     Raw(u8),
1699 }
1700
1701 /// An AST literal.
1702 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1703 pub struct Lit {
1704     /// The original literal token as written in source code.
1705     pub token_lit: token::Lit,
1706     /// The "semantic" representation of the literal lowered from the original tokens.
1707     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1708     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1709     pub kind: LitKind,
1710     pub span: Span,
1711 }
1712
1713 /// Same as `Lit`, but restricted to string literals.
1714 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1715 pub struct StrLit {
1716     /// The original literal token as written in source code.
1717     pub style: StrStyle,
1718     pub symbol: Symbol,
1719     pub suffix: Option<Symbol>,
1720     pub span: Span,
1721     /// The unescaped "semantic" representation of the literal lowered from the original token.
1722     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1723     pub symbol_unescaped: Symbol,
1724 }
1725
1726 impl StrLit {
1727     pub fn as_token_lit(&self) -> token::Lit {
1728         let token_kind = match self.style {
1729             StrStyle::Cooked => token::Str,
1730             StrStyle::Raw(n) => token::StrRaw(n),
1731         };
1732         token::Lit::new(token_kind, self.symbol, self.suffix)
1733     }
1734 }
1735
1736 /// Type of the integer literal based on provided suffix.
1737 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1738 #[derive(HashStable_Generic)]
1739 pub enum LitIntType {
1740     /// e.g. `42_i32`.
1741     Signed(IntTy),
1742     /// e.g. `42_u32`.
1743     Unsigned(UintTy),
1744     /// e.g. `42`.
1745     Unsuffixed,
1746 }
1747
1748 /// Type of the float literal based on provided suffix.
1749 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1750 #[derive(HashStable_Generic)]
1751 pub enum LitFloatType {
1752     /// A float literal with a suffix (`1f32` or `1E10f32`).
1753     Suffixed(FloatTy),
1754     /// A float literal without a suffix (`1.0 or 1.0E10`).
1755     Unsuffixed,
1756 }
1757
1758 /// Note that the entire literal (including the suffix) is considered when
1759 /// deciding the `LitKind`. This means that float literals like `1f32` are
1760 /// classified by this type as `Float`. This is different to `token::LitKind`
1761 /// which does *not* consider the suffix.
1762 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1763 pub enum LitKind {
1764     /// A string literal (`"foo"`). The symbol is unescaped, and so may differ
1765     /// from the original token's symbol.
1766     Str(Symbol, StrStyle),
1767     /// A byte string (`b"foo"`).
1768     ByteStr(Lrc<[u8]>),
1769     /// A byte char (`b'f'`).
1770     Byte(u8),
1771     /// A character literal (`'a'`).
1772     Char(char),
1773     /// An integer literal (`1`).
1774     Int(u128, LitIntType),
1775     /// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
1776     /// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
1777     /// and `Hash`.
1778     Float(Symbol, LitFloatType),
1779     /// A boolean literal (`true`, `false`).
1780     Bool(bool),
1781     /// Placeholder for a literal that wasn't well-formed in some way.
1782     Err,
1783 }
1784
1785 impl LitKind {
1786     /// Returns `true` if this literal is a string.
1787     pub fn is_str(&self) -> bool {
1788         matches!(self, LitKind::Str(..))
1789     }
1790
1791     /// Returns `true` if this literal is byte literal string.
1792     pub fn is_bytestr(&self) -> bool {
1793         matches!(self, LitKind::ByteStr(_))
1794     }
1795
1796     /// Returns `true` if this is a numeric literal.
1797     pub fn is_numeric(&self) -> bool {
1798         matches!(self, LitKind::Int(..) | LitKind::Float(..))
1799     }
1800
1801     /// Returns `true` if this literal has no suffix.
1802     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1803     pub fn is_unsuffixed(&self) -> bool {
1804         !self.is_suffixed()
1805     }
1806
1807     /// Returns `true` if this literal has a suffix.
1808     pub fn is_suffixed(&self) -> bool {
1809         match *self {
1810             // suffixed variants
1811             LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1812             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1813             // unsuffixed variants
1814             LitKind::Str(..)
1815             | LitKind::ByteStr(..)
1816             | LitKind::Byte(..)
1817             | LitKind::Char(..)
1818             | LitKind::Int(_, LitIntType::Unsuffixed)
1819             | LitKind::Float(_, LitFloatType::Unsuffixed)
1820             | LitKind::Bool(..)
1821             | LitKind::Err => false,
1822         }
1823     }
1824 }
1825
1826 // N.B., If you change this, you'll probably want to change the corresponding
1827 // type structure in `middle/ty.rs` as well.
1828 #[derive(Clone, Encodable, Decodable, Debug)]
1829 pub struct MutTy {
1830     pub ty: P<Ty>,
1831     pub mutbl: Mutability,
1832 }
1833
1834 /// Represents a function's signature in a trait declaration,
1835 /// trait implementation, or free function.
1836 #[derive(Clone, Encodable, Decodable, Debug)]
1837 pub struct FnSig {
1838     pub header: FnHeader,
1839     pub decl: P<FnDecl>,
1840     pub span: Span,
1841 }
1842
1843 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1844 #[derive(Encodable, Decodable, HashStable_Generic)]
1845 pub enum FloatTy {
1846     F32,
1847     F64,
1848 }
1849
1850 impl FloatTy {
1851     pub fn name_str(self) -> &'static str {
1852         match self {
1853             FloatTy::F32 => "f32",
1854             FloatTy::F64 => "f64",
1855         }
1856     }
1857
1858     pub fn name(self) -> Symbol {
1859         match self {
1860             FloatTy::F32 => sym::f32,
1861             FloatTy::F64 => sym::f64,
1862         }
1863     }
1864 }
1865
1866 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1867 #[derive(Encodable, Decodable, HashStable_Generic)]
1868 pub enum IntTy {
1869     Isize,
1870     I8,
1871     I16,
1872     I32,
1873     I64,
1874     I128,
1875 }
1876
1877 impl IntTy {
1878     pub fn name_str(&self) -> &'static str {
1879         match *self {
1880             IntTy::Isize => "isize",
1881             IntTy::I8 => "i8",
1882             IntTy::I16 => "i16",
1883             IntTy::I32 => "i32",
1884             IntTy::I64 => "i64",
1885             IntTy::I128 => "i128",
1886         }
1887     }
1888
1889     pub fn name(&self) -> Symbol {
1890         match *self {
1891             IntTy::Isize => sym::isize,
1892             IntTy::I8 => sym::i8,
1893             IntTy::I16 => sym::i16,
1894             IntTy::I32 => sym::i32,
1895             IntTy::I64 => sym::i64,
1896             IntTy::I128 => sym::i128,
1897         }
1898     }
1899 }
1900
1901 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1902 #[derive(Encodable, Decodable, HashStable_Generic)]
1903 pub enum UintTy {
1904     Usize,
1905     U8,
1906     U16,
1907     U32,
1908     U64,
1909     U128,
1910 }
1911
1912 impl UintTy {
1913     pub fn name_str(&self) -> &'static str {
1914         match *self {
1915             UintTy::Usize => "usize",
1916             UintTy::U8 => "u8",
1917             UintTy::U16 => "u16",
1918             UintTy::U32 => "u32",
1919             UintTy::U64 => "u64",
1920             UintTy::U128 => "u128",
1921         }
1922     }
1923
1924     pub fn name(&self) -> Symbol {
1925         match *self {
1926             UintTy::Usize => sym::usize,
1927             UintTy::U8 => sym::u8,
1928             UintTy::U16 => sym::u16,
1929             UintTy::U32 => sym::u32,
1930             UintTy::U64 => sym::u64,
1931             UintTy::U128 => sym::u128,
1932         }
1933     }
1934 }
1935
1936 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1937 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1938 #[derive(Clone, Encodable, Decodable, Debug)]
1939 pub struct AssocConstraint {
1940     pub id: NodeId,
1941     pub ident: Ident,
1942     pub gen_args: Option<GenericArgs>,
1943     pub kind: AssocConstraintKind,
1944     pub span: Span,
1945 }
1946
1947 /// The kinds of an `AssocConstraint`.
1948 #[derive(Clone, Encodable, Decodable, Debug)]
1949 pub enum Term {
1950     Ty(P<Ty>),
1951     Const(AnonConst),
1952 }
1953
1954 impl From<P<Ty>> for Term {
1955     fn from(v: P<Ty>) -> Self {
1956         Term::Ty(v)
1957     }
1958 }
1959
1960 impl From<AnonConst> for Term {
1961     fn from(v: AnonConst) -> Self {
1962         Term::Const(v)
1963     }
1964 }
1965
1966 /// The kinds of an `AssocConstraint`.
1967 #[derive(Clone, Encodable, Decodable, Debug)]
1968 pub enum AssocConstraintKind {
1969     /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1970     Equality { term: Term },
1971     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1972     Bound { bounds: GenericBounds },
1973 }
1974
1975 #[derive(Encodable, Decodable, Debug)]
1976 pub struct Ty {
1977     pub id: NodeId,
1978     pub kind: TyKind,
1979     pub span: Span,
1980     pub tokens: Option<LazyAttrTokenStream>,
1981 }
1982
1983 impl Clone for Ty {
1984     fn clone(&self) -> Self {
1985         ensure_sufficient_stack(|| Self {
1986             id: self.id,
1987             kind: self.kind.clone(),
1988             span: self.span,
1989             tokens: self.tokens.clone(),
1990         })
1991     }
1992 }
1993
1994 impl Ty {
1995     pub fn peel_refs(&self) -> &Self {
1996         let mut final_ty = self;
1997         while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1998             final_ty = &ty;
1999         }
2000         final_ty
2001     }
2002 }
2003
2004 #[derive(Clone, Encodable, Decodable, Debug)]
2005 pub struct BareFnTy {
2006     pub unsafety: Unsafe,
2007     pub ext: Extern,
2008     pub generic_params: Vec<GenericParam>,
2009     pub decl: P<FnDecl>,
2010     /// Span of the `fn(...) -> ...` part.
2011     pub decl_span: Span,
2012 }
2013
2014 /// The various kinds of type recognized by the compiler.
2015 #[derive(Clone, Encodable, Decodable, Debug)]
2016 pub enum TyKind {
2017     /// A variable-length slice (`[T]`).
2018     Slice(P<Ty>),
2019     /// A fixed length array (`[T; n]`).
2020     Array(P<Ty>, AnonConst),
2021     /// A raw pointer (`*const T` or `*mut T`).
2022     Ptr(MutTy),
2023     /// A reference (`&'a T` or `&'a mut T`).
2024     Rptr(Option<Lifetime>, MutTy),
2025     /// A bare function (e.g., `fn(usize) -> bool`).
2026     BareFn(P<BareFnTy>),
2027     /// The never type (`!`).
2028     Never,
2029     /// A tuple (`(A, B, C, D,...)`).
2030     Tup(Vec<P<Ty>>),
2031     /// A path (`module::module::...::Type`), optionally
2032     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2033     ///
2034     /// Type parameters are stored in the `Path` itself.
2035     Path(Option<P<QSelf>>, Path),
2036     /// A trait object type `Bound1 + Bound2 + Bound3`
2037     /// where `Bound` is a trait or a lifetime.
2038     TraitObject(GenericBounds, TraitObjectSyntax),
2039     /// An `impl Bound1 + Bound2 + Bound3` type
2040     /// where `Bound` is a trait or a lifetime.
2041     ///
2042     /// The `NodeId` exists to prevent lowering from having to
2043     /// generate `NodeId`s on the fly, which would complicate
2044     /// the generation of opaque `type Foo = impl Trait` items significantly.
2045     ImplTrait(NodeId, GenericBounds),
2046     /// No-op; kept solely so that we can pretty-print faithfully.
2047     Paren(P<Ty>),
2048     /// Unused for now.
2049     Typeof(AnonConst),
2050     /// This means the type should be inferred instead of it having been
2051     /// specified. This can appear anywhere in a type.
2052     Infer,
2053     /// Inferred type of a `self` or `&self` argument in a method.
2054     ImplicitSelf,
2055     /// A macro in the type position.
2056     MacCall(P<MacCall>),
2057     /// Placeholder for a kind that has failed to be defined.
2058     Err,
2059     /// Placeholder for a `va_list`.
2060     CVarArgs,
2061 }
2062
2063 impl TyKind {
2064     pub fn is_implicit_self(&self) -> bool {
2065         matches!(self, TyKind::ImplicitSelf)
2066     }
2067
2068     pub fn is_unit(&self) -> bool {
2069         matches!(self, TyKind::Tup(tys) if tys.is_empty())
2070     }
2071
2072     pub fn is_simple_path(&self) -> Option<Symbol> {
2073         if let TyKind::Path(None, Path { segments, .. }) = &self
2074             && let [segment] = &segments[..]
2075             && segment.args.is_none()
2076         {
2077             Some(segment.ident.name)
2078         } else {
2079             None
2080         }
2081     }
2082 }
2083
2084 /// Syntax used to declare a trait object.
2085 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2086 pub enum TraitObjectSyntax {
2087     Dyn,
2088     DynStar,
2089     None,
2090 }
2091
2092 /// Inline assembly operand explicit register or register class.
2093 ///
2094 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2095 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2096 pub enum InlineAsmRegOrRegClass {
2097     Reg(Symbol),
2098     RegClass(Symbol),
2099 }
2100
2101 bitflags::bitflags! {
2102     #[derive(Encodable, Decodable, HashStable_Generic)]
2103     pub struct InlineAsmOptions: u16 {
2104         const PURE            = 1 << 0;
2105         const NOMEM           = 1 << 1;
2106         const READONLY        = 1 << 2;
2107         const PRESERVES_FLAGS = 1 << 3;
2108         const NORETURN        = 1 << 4;
2109         const NOSTACK         = 1 << 5;
2110         const ATT_SYNTAX      = 1 << 6;
2111         const RAW             = 1 << 7;
2112         const MAY_UNWIND      = 1 << 8;
2113     }
2114 }
2115
2116 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2117 pub enum InlineAsmTemplatePiece {
2118     String(String),
2119     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2120 }
2121
2122 impl fmt::Display for InlineAsmTemplatePiece {
2123     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2124         match self {
2125             Self::String(s) => {
2126                 for c in s.chars() {
2127                     match c {
2128                         '{' => f.write_str("{{")?,
2129                         '}' => f.write_str("}}")?,
2130                         _ => c.fmt(f)?,
2131                     }
2132                 }
2133                 Ok(())
2134             }
2135             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2136                 write!(f, "{{{}:{}}}", operand_idx, modifier)
2137             }
2138             Self::Placeholder { operand_idx, modifier: None, .. } => {
2139                 write!(f, "{{{}}}", operand_idx)
2140             }
2141         }
2142     }
2143 }
2144
2145 impl InlineAsmTemplatePiece {
2146     /// Rebuilds the asm template string from its pieces.
2147     pub fn to_string(s: &[Self]) -> String {
2148         use fmt::Write;
2149         let mut out = String::new();
2150         for p in s.iter() {
2151             let _ = write!(out, "{}", p);
2152         }
2153         out
2154     }
2155 }
2156
2157 /// Inline assembly symbol operands get their own AST node that is somewhat
2158 /// similar to `AnonConst`.
2159 ///
2160 /// The main difference is that we specifically don't assign it `DefId` in
2161 /// `DefCollector`. Instead this is deferred until AST lowering where we
2162 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2163 /// depending on what the path resolves to.
2164 #[derive(Clone, Encodable, Decodable, Debug)]
2165 pub struct InlineAsmSym {
2166     pub id: NodeId,
2167     pub qself: Option<P<QSelf>>,
2168     pub path: Path,
2169 }
2170
2171 /// Inline assembly operand.
2172 ///
2173 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2174 #[derive(Clone, Encodable, Decodable, Debug)]
2175 pub enum InlineAsmOperand {
2176     In {
2177         reg: InlineAsmRegOrRegClass,
2178         expr: P<Expr>,
2179     },
2180     Out {
2181         reg: InlineAsmRegOrRegClass,
2182         late: bool,
2183         expr: Option<P<Expr>>,
2184     },
2185     InOut {
2186         reg: InlineAsmRegOrRegClass,
2187         late: bool,
2188         expr: P<Expr>,
2189     },
2190     SplitInOut {
2191         reg: InlineAsmRegOrRegClass,
2192         late: bool,
2193         in_expr: P<Expr>,
2194         out_expr: Option<P<Expr>>,
2195     },
2196     Const {
2197         anon_const: AnonConst,
2198     },
2199     Sym {
2200         sym: InlineAsmSym,
2201     },
2202 }
2203
2204 /// Inline assembly.
2205 ///
2206 /// E.g., `asm!("NOP");`.
2207 #[derive(Clone, Encodable, Decodable, Debug)]
2208 pub struct InlineAsm {
2209     pub template: Vec<InlineAsmTemplatePiece>,
2210     pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2211     pub operands: Vec<(InlineAsmOperand, Span)>,
2212     pub clobber_abis: Vec<(Symbol, Span)>,
2213     pub options: InlineAsmOptions,
2214     pub line_spans: Vec<Span>,
2215 }
2216
2217 /// A parameter in a function header.
2218 ///
2219 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2220 #[derive(Clone, Encodable, Decodable, Debug)]
2221 pub struct Param {
2222     pub attrs: AttrVec,
2223     pub ty: P<Ty>,
2224     pub pat: P<Pat>,
2225     pub id: NodeId,
2226     pub span: Span,
2227     pub is_placeholder: bool,
2228 }
2229
2230 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2231 ///
2232 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2233 #[derive(Clone, Encodable, Decodable, Debug)]
2234 pub enum SelfKind {
2235     /// `self`, `mut self`
2236     Value(Mutability),
2237     /// `&'lt self`, `&'lt mut self`
2238     Region(Option<Lifetime>, Mutability),
2239     /// `self: TYPE`, `mut self: TYPE`
2240     Explicit(P<Ty>, Mutability),
2241 }
2242
2243 pub type ExplicitSelf = Spanned<SelfKind>;
2244
2245 impl Param {
2246     /// Attempts to cast parameter to `ExplicitSelf`.
2247     pub fn to_self(&self) -> Option<ExplicitSelf> {
2248         if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2249             if ident.name == kw::SelfLower {
2250                 return match self.ty.kind {
2251                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2252                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2253                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2254                     }
2255                     _ => Some(respan(
2256                         self.pat.span.to(self.ty.span),
2257                         SelfKind::Explicit(self.ty.clone(), mutbl),
2258                     )),
2259                 };
2260             }
2261         }
2262         None
2263     }
2264
2265     /// Returns `true` if parameter is `self`.
2266     pub fn is_self(&self) -> bool {
2267         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2268             ident.name == kw::SelfLower
2269         } else {
2270             false
2271         }
2272     }
2273
2274     /// Builds a `Param` object from `ExplicitSelf`.
2275     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2276         let span = eself.span.to(eself_ident.span);
2277         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2278         let (mutbl, ty) = match eself.node {
2279             SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2280             SelfKind::Value(mutbl) => (mutbl, infer_ty),
2281             SelfKind::Region(lt, mutbl) => (
2282                 Mutability::Not,
2283                 P(Ty {
2284                     id: DUMMY_NODE_ID,
2285                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2286                     span,
2287                     tokens: None,
2288                 }),
2289             ),
2290         };
2291         Param {
2292             attrs,
2293             pat: P(Pat {
2294                 id: DUMMY_NODE_ID,
2295                 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2296                 span,
2297                 tokens: None,
2298             }),
2299             span,
2300             ty,
2301             id: DUMMY_NODE_ID,
2302             is_placeholder: false,
2303         }
2304     }
2305 }
2306
2307 /// A signature (not the body) of a function declaration.
2308 ///
2309 /// E.g., `fn foo(bar: baz)`.
2310 ///
2311 /// Please note that it's different from `FnHeader` structure
2312 /// which contains metadata about function safety, asyncness, constness and ABI.
2313 #[derive(Clone, Encodable, Decodable, Debug)]
2314 pub struct FnDecl {
2315     pub inputs: Vec<Param>,
2316     pub output: FnRetTy,
2317 }
2318
2319 impl FnDecl {
2320     pub fn has_self(&self) -> bool {
2321         self.inputs.get(0).map_or(false, Param::is_self)
2322     }
2323     pub fn c_variadic(&self) -> bool {
2324         self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2325     }
2326 }
2327
2328 /// Is the trait definition an auto trait?
2329 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2330 pub enum IsAuto {
2331     Yes,
2332     No,
2333 }
2334
2335 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2336 #[derive(HashStable_Generic)]
2337 pub enum Unsafe {
2338     Yes(Span),
2339     No,
2340 }
2341
2342 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2343 pub enum Async {
2344     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2345     No,
2346 }
2347
2348 impl Async {
2349     pub fn is_async(self) -> bool {
2350         matches!(self, Async::Yes { .. })
2351     }
2352
2353     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2354     pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2355         match self {
2356             Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2357             Async::No => None,
2358         }
2359     }
2360 }
2361
2362 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2363 #[derive(HashStable_Generic)]
2364 pub enum Const {
2365     Yes(Span),
2366     No,
2367 }
2368
2369 /// Item defaultness.
2370 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2371 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2372 pub enum Defaultness {
2373     Default(Span),
2374     Final,
2375 }
2376
2377 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2378 pub enum ImplPolarity {
2379     /// `impl Trait for Type`
2380     Positive,
2381     /// `impl !Trait for Type`
2382     Negative(Span),
2383 }
2384
2385 impl fmt::Debug for ImplPolarity {
2386     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2387         match *self {
2388             ImplPolarity::Positive => "positive".fmt(f),
2389             ImplPolarity::Negative(_) => "negative".fmt(f),
2390         }
2391     }
2392 }
2393
2394 #[derive(Clone, Encodable, Decodable, Debug)]
2395 pub enum FnRetTy {
2396     /// Returns type is not specified.
2397     ///
2398     /// Functions default to `()` and closures default to inference.
2399     /// Span points to where return type would be inserted.
2400     Default(Span),
2401     /// Everything else.
2402     Ty(P<Ty>),
2403 }
2404
2405 impl FnRetTy {
2406     pub fn span(&self) -> Span {
2407         match self {
2408             &FnRetTy::Default(span) => span,
2409             FnRetTy::Ty(ty) => ty.span,
2410         }
2411     }
2412 }
2413
2414 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2415 pub enum Inline {
2416     Yes,
2417     No,
2418 }
2419
2420 /// Module item kind.
2421 #[derive(Clone, Encodable, Decodable, Debug)]
2422 pub enum ModKind {
2423     /// Module with inlined definition `mod foo { ... }`,
2424     /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2425     /// The inner span is from the first token past `{` to the last token until `}`,
2426     /// or from the first to the last token in the loaded file.
2427     Loaded(Vec<P<Item>>, Inline, ModSpans),
2428     /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2429     Unloaded,
2430 }
2431
2432 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2433 pub struct ModSpans {
2434     /// `inner_span` covers the body of the module; for a file module, its the whole file.
2435     /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2436     pub inner_span: Span,
2437     pub inject_use_span: Span,
2438 }
2439
2440 impl Default for ModSpans {
2441     fn default() -> ModSpans {
2442         ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2443     }
2444 }
2445
2446 /// Foreign module declaration.
2447 ///
2448 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2449 #[derive(Clone, Encodable, Decodable, Debug)]
2450 pub struct ForeignMod {
2451     /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2452     /// semantically by Rust.
2453     pub unsafety: Unsafe,
2454     pub abi: Option<StrLit>,
2455     pub items: Vec<P<ForeignItem>>,
2456 }
2457
2458 #[derive(Clone, Encodable, Decodable, Debug)]
2459 pub struct EnumDef {
2460     pub variants: Vec<Variant>,
2461 }
2462 /// Enum variant.
2463 #[derive(Clone, Encodable, Decodable, Debug)]
2464 pub struct Variant {
2465     /// Attributes of the variant.
2466     pub attrs: AttrVec,
2467     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2468     pub id: NodeId,
2469     /// Span
2470     pub span: Span,
2471     /// The visibility of the variant. Syntactically accepted but not semantically.
2472     pub vis: Visibility,
2473     /// Name of the variant.
2474     pub ident: Ident,
2475
2476     /// Fields and constructor id of the variant.
2477     pub data: VariantData,
2478     /// Explicit discriminant, e.g., `Foo = 1`.
2479     pub disr_expr: Option<AnonConst>,
2480     /// Is a macro placeholder
2481     pub is_placeholder: bool,
2482 }
2483
2484 /// Part of `use` item to the right of its prefix.
2485 #[derive(Clone, Encodable, Decodable, Debug)]
2486 pub enum UseTreeKind {
2487     /// `use prefix` or `use prefix as rename`
2488     ///
2489     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2490     /// namespace.
2491     Simple(Option<Ident>, NodeId, NodeId),
2492     /// `use prefix::{...}`
2493     Nested(Vec<(UseTree, NodeId)>),
2494     /// `use prefix::*`
2495     Glob,
2496 }
2497
2498 /// A tree of paths sharing common prefixes.
2499 /// Used in `use` items both at top-level and inside of braces in import groups.
2500 #[derive(Clone, Encodable, Decodable, Debug)]
2501 pub struct UseTree {
2502     pub prefix: Path,
2503     pub kind: UseTreeKind,
2504     pub span: Span,
2505 }
2506
2507 impl UseTree {
2508     pub fn ident(&self) -> Ident {
2509         match self.kind {
2510             UseTreeKind::Simple(Some(rename), ..) => rename,
2511             UseTreeKind::Simple(None, ..) => {
2512                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2513             }
2514             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2515         }
2516     }
2517 }
2518
2519 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2520 /// are contained as statements within items. These two cases need to be
2521 /// distinguished for pretty-printing.
2522 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2523 pub enum AttrStyle {
2524     Outer,
2525     Inner,
2526 }
2527
2528 rustc_index::newtype_index! {
2529     pub struct AttrId {
2530         ENCODABLE = custom
2531         DEBUG_FORMAT = "AttrId({})"
2532     }
2533 }
2534
2535 impl<S: Encoder> Encodable<S> for AttrId {
2536     fn encode(&self, _s: &mut S) {}
2537 }
2538
2539 impl<D: Decoder> Decodable<D> for AttrId {
2540     default fn decode(_: &mut D) -> AttrId {
2541         panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2542     }
2543 }
2544
2545 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2546 pub struct AttrItem {
2547     pub path: Path,
2548     pub args: AttrArgs,
2549     pub tokens: Option<LazyAttrTokenStream>,
2550 }
2551
2552 /// A list of attributes.
2553 pub type AttrVec = ThinVec<Attribute>;
2554
2555 /// Metadata associated with an item.
2556 #[derive(Clone, Encodable, Decodable, Debug)]
2557 pub struct Attribute {
2558     pub kind: AttrKind,
2559     pub id: AttrId,
2560     /// Denotes if the attribute decorates the following construct (outer)
2561     /// or the construct this attribute is contained within (inner).
2562     pub style: AttrStyle,
2563     pub span: Span,
2564 }
2565
2566 #[derive(Clone, Encodable, Decodable, Debug)]
2567 pub struct NormalAttr {
2568     pub item: AttrItem,
2569     pub tokens: Option<LazyAttrTokenStream>,
2570 }
2571
2572 #[derive(Clone, Encodable, Decodable, Debug)]
2573 pub enum AttrKind {
2574     /// A normal attribute.
2575     Normal(P<NormalAttr>),
2576
2577     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2578     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2579     /// variant (which is much less compact and thus more expensive).
2580     DocComment(CommentKind, Symbol),
2581 }
2582
2583 /// `TraitRef`s appear in impls.
2584 ///
2585 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2586 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2587 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2588 /// same as the impl's `NodeId`).
2589 #[derive(Clone, Encodable, Decodable, Debug)]
2590 pub struct TraitRef {
2591     pub path: Path,
2592     pub ref_id: NodeId,
2593 }
2594
2595 #[derive(Clone, Encodable, Decodable, Debug)]
2596 pub struct PolyTraitRef {
2597     /// The `'a` in `for<'a> Foo<&'a T>`.
2598     pub bound_generic_params: Vec<GenericParam>,
2599
2600     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2601     pub trait_ref: TraitRef,
2602
2603     pub span: Span,
2604 }
2605
2606 impl PolyTraitRef {
2607     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2608         PolyTraitRef {
2609             bound_generic_params: generic_params,
2610             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2611             span,
2612         }
2613     }
2614 }
2615
2616 #[derive(Clone, Encodable, Decodable, Debug)]
2617 pub struct Visibility {
2618     pub kind: VisibilityKind,
2619     pub span: Span,
2620     pub tokens: Option<LazyAttrTokenStream>,
2621 }
2622
2623 #[derive(Clone, Encodable, Decodable, Debug)]
2624 pub enum VisibilityKind {
2625     Public,
2626     Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2627     Inherited,
2628 }
2629
2630 impl VisibilityKind {
2631     pub fn is_pub(&self) -> bool {
2632         matches!(self, VisibilityKind::Public)
2633     }
2634 }
2635
2636 /// Field definition in a struct, variant or union.
2637 ///
2638 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2639 #[derive(Clone, Encodable, Decodable, Debug)]
2640 pub struct FieldDef {
2641     pub attrs: AttrVec,
2642     pub id: NodeId,
2643     pub span: Span,
2644     pub vis: Visibility,
2645     pub ident: Option<Ident>,
2646
2647     pub ty: P<Ty>,
2648     pub is_placeholder: bool,
2649 }
2650
2651 /// Fields and constructor ids of enum variants and structs.
2652 #[derive(Clone, Encodable, Decodable, Debug)]
2653 pub enum VariantData {
2654     /// Struct variant.
2655     ///
2656     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2657     Struct(Vec<FieldDef>, bool),
2658     /// Tuple variant.
2659     ///
2660     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2661     Tuple(Vec<FieldDef>, NodeId),
2662     /// Unit variant.
2663     ///
2664     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2665     Unit(NodeId),
2666 }
2667
2668 impl VariantData {
2669     /// Return the fields of this variant.
2670     pub fn fields(&self) -> &[FieldDef] {
2671         match self {
2672             VariantData::Struct(fields, ..) | VariantData::Tuple(fields, _) => fields,
2673             _ => &[],
2674         }
2675     }
2676
2677     /// Return the `NodeId` of this variant's constructor, if it has one.
2678     pub fn ctor_node_id(&self) -> Option<NodeId> {
2679         match *self {
2680             VariantData::Struct(..) => None,
2681             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2682         }
2683     }
2684 }
2685
2686 /// An item definition.
2687 #[derive(Clone, Encodable, Decodable, Debug)]
2688 pub struct Item<K = ItemKind> {
2689     pub attrs: AttrVec,
2690     pub id: NodeId,
2691     pub span: Span,
2692     pub vis: Visibility,
2693     /// The name of the item.
2694     /// It might be a dummy name in case of anonymous items.
2695     pub ident: Ident,
2696
2697     pub kind: K,
2698
2699     /// Original tokens this item was parsed from. This isn't necessarily
2700     /// available for all items, although over time more and more items should
2701     /// have this be `Some`. Right now this is primarily used for procedural
2702     /// macros, notably custom attributes.
2703     ///
2704     /// Note that the tokens here do not include the outer attributes, but will
2705     /// include inner attributes.
2706     pub tokens: Option<LazyAttrTokenStream>,
2707 }
2708
2709 impl Item {
2710     /// Return the span that encompasses the attributes.
2711     pub fn span_with_attributes(&self) -> Span {
2712         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2713     }
2714 }
2715
2716 /// `extern` qualifier on a function item or function type.
2717 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2718 pub enum Extern {
2719     None,
2720     Implicit(Span),
2721     Explicit(StrLit, Span),
2722 }
2723
2724 impl Extern {
2725     pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2726         match abi {
2727             Some(name) => Extern::Explicit(name, span),
2728             None => Extern::Implicit(span),
2729         }
2730     }
2731 }
2732
2733 /// A function header.
2734 ///
2735 /// All the information between the visibility and the name of the function is
2736 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2737 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2738 pub struct FnHeader {
2739     pub unsafety: Unsafe,
2740     pub asyncness: Async,
2741     pub constness: Const,
2742     pub ext: Extern,
2743 }
2744
2745 impl FnHeader {
2746     /// Does this function header have any qualifiers or is it empty?
2747     pub fn has_qualifiers(&self) -> bool {
2748         let Self { unsafety, asyncness, constness, ext } = self;
2749         matches!(unsafety, Unsafe::Yes(_))
2750             || asyncness.is_async()
2751             || matches!(constness, Const::Yes(_))
2752             || !matches!(ext, Extern::None)
2753     }
2754 }
2755
2756 impl Default for FnHeader {
2757     fn default() -> FnHeader {
2758         FnHeader {
2759             unsafety: Unsafe::No,
2760             asyncness: Async::No,
2761             constness: Const::No,
2762             ext: Extern::None,
2763         }
2764     }
2765 }
2766
2767 #[derive(Clone, Encodable, Decodable, Debug)]
2768 pub struct Trait {
2769     pub unsafety: Unsafe,
2770     pub is_auto: IsAuto,
2771     pub generics: Generics,
2772     pub bounds: GenericBounds,
2773     pub items: Vec<P<AssocItem>>,
2774 }
2775
2776 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2777 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2778 /// are two locations for where clause on type aliases, but their predicates
2779 /// are concatenated together.
2780 ///
2781 /// Take this example:
2782 /// ```ignore (only-for-syntax-highlight)
2783 /// trait Foo {
2784 ///   type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2785 /// }
2786 /// impl Foo for () {
2787 ///   type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2788 ///   //                 ^^^^^^^^^^^^^^ first where clause
2789 ///   //                                     ^^^^^^^^^^^^^^ second where clause
2790 /// }
2791 /// ```
2792 ///
2793 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2794 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2795 pub struct TyAliasWhereClause(pub bool, pub Span);
2796
2797 #[derive(Clone, Encodable, Decodable, Debug)]
2798 pub struct TyAlias {
2799     pub defaultness: Defaultness,
2800     pub generics: Generics,
2801     /// The span information for the two where clauses (before equals, after equals)
2802     pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2803     /// The index in `generics.where_clause.predicates` that would split into
2804     /// predicates from the where clause before the equals and the predicates
2805     /// from the where clause after the equals
2806     pub where_predicates_split: usize,
2807     pub bounds: GenericBounds,
2808     pub ty: Option<P<Ty>>,
2809 }
2810
2811 #[derive(Clone, Encodable, Decodable, Debug)]
2812 pub struct Impl {
2813     pub defaultness: Defaultness,
2814     pub unsafety: Unsafe,
2815     pub generics: Generics,
2816     pub constness: Const,
2817     pub polarity: ImplPolarity,
2818     /// The trait being implemented, if any.
2819     pub of_trait: Option<TraitRef>,
2820     pub self_ty: P<Ty>,
2821     pub items: Vec<P<AssocItem>>,
2822 }
2823
2824 #[derive(Clone, Encodable, Decodable, Debug)]
2825 pub struct Fn {
2826     pub defaultness: Defaultness,
2827     pub generics: Generics,
2828     pub sig: FnSig,
2829     pub body: Option<P<Block>>,
2830 }
2831
2832 #[derive(Clone, Encodable, Decodable, Debug)]
2833 pub enum ItemKind {
2834     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2835     ///
2836     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2837     ExternCrate(Option<Symbol>),
2838     /// A use declaration item (`use`).
2839     ///
2840     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2841     Use(UseTree),
2842     /// A static item (`static`).
2843     ///
2844     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2845     Static(P<Ty>, Mutability, Option<P<Expr>>),
2846     /// A constant item (`const`).
2847     ///
2848     /// E.g., `const FOO: i32 = 42;`.
2849     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2850     /// A function declaration (`fn`).
2851     ///
2852     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2853     Fn(Box<Fn>),
2854     /// A module declaration (`mod`).
2855     ///
2856     /// E.g., `mod foo;` or `mod foo { .. }`.
2857     /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2858     /// semantically by Rust.
2859     Mod(Unsafe, ModKind),
2860     /// An external module (`extern`).
2861     ///
2862     /// E.g., `extern {}` or `extern "C" {}`.
2863     ForeignMod(ForeignMod),
2864     /// Module-level inline assembly (from `global_asm!()`).
2865     GlobalAsm(Box<InlineAsm>),
2866     /// A type alias (`type`).
2867     ///
2868     /// E.g., `type Foo = Bar<u8>;`.
2869     TyAlias(Box<TyAlias>),
2870     /// An enum definition (`enum`).
2871     ///
2872     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2873     Enum(EnumDef, Generics),
2874     /// A struct definition (`struct`).
2875     ///
2876     /// E.g., `struct Foo<A> { x: A }`.
2877     Struct(VariantData, Generics),
2878     /// A union definition (`union`).
2879     ///
2880     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2881     Union(VariantData, Generics),
2882     /// A trait declaration (`trait`).
2883     ///
2884     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2885     Trait(Box<Trait>),
2886     /// Trait alias
2887     ///
2888     /// E.g., `trait Foo = Bar + Quux;`.
2889     TraitAlias(Generics, GenericBounds),
2890     /// An implementation.
2891     ///
2892     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2893     Impl(Box<Impl>),
2894     /// A macro invocation.
2895     ///
2896     /// E.g., `foo!(..)`.
2897     MacCall(P<MacCall>),
2898
2899     /// A macro definition.
2900     MacroDef(MacroDef),
2901 }
2902
2903 impl ItemKind {
2904     pub fn article(&self) -> &str {
2905         use ItemKind::*;
2906         match self {
2907             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2908             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2909             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2910         }
2911     }
2912
2913     pub fn descr(&self) -> &str {
2914         match self {
2915             ItemKind::ExternCrate(..) => "extern crate",
2916             ItemKind::Use(..) => "`use` import",
2917             ItemKind::Static(..) => "static item",
2918             ItemKind::Const(..) => "constant item",
2919             ItemKind::Fn(..) => "function",
2920             ItemKind::Mod(..) => "module",
2921             ItemKind::ForeignMod(..) => "extern block",
2922             ItemKind::GlobalAsm(..) => "global asm item",
2923             ItemKind::TyAlias(..) => "type alias",
2924             ItemKind::Enum(..) => "enum",
2925             ItemKind::Struct(..) => "struct",
2926             ItemKind::Union(..) => "union",
2927             ItemKind::Trait(..) => "trait",
2928             ItemKind::TraitAlias(..) => "trait alias",
2929             ItemKind::MacCall(..) => "item macro invocation",
2930             ItemKind::MacroDef(..) => "macro definition",
2931             ItemKind::Impl { .. } => "implementation",
2932         }
2933     }
2934
2935     pub fn generics(&self) -> Option<&Generics> {
2936         match self {
2937             Self::Fn(box Fn { generics, .. })
2938             | Self::TyAlias(box TyAlias { generics, .. })
2939             | Self::Enum(_, generics)
2940             | Self::Struct(_, generics)
2941             | Self::Union(_, generics)
2942             | Self::Trait(box Trait { generics, .. })
2943             | Self::TraitAlias(generics, _)
2944             | Self::Impl(box Impl { generics, .. }) => Some(generics),
2945             _ => None,
2946         }
2947     }
2948 }
2949
2950 /// Represents associated items.
2951 /// These include items in `impl` and `trait` definitions.
2952 pub type AssocItem = Item<AssocItemKind>;
2953
2954 /// Represents associated item kinds.
2955 ///
2956 /// The term "provided" in the variants below refers to the item having a default
2957 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2958 /// In an implementation, all items must be provided.
2959 /// The `Option`s below denote the bodies, where `Some(_)`
2960 /// means "provided" and conversely `None` means "required".
2961 #[derive(Clone, Encodable, Decodable, Debug)]
2962 pub enum AssocItemKind {
2963     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2964     /// If `def` is parsed, then the constant is provided, and otherwise required.
2965     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2966     /// An associated function.
2967     Fn(Box<Fn>),
2968     /// An associated type.
2969     Type(Box<TyAlias>),
2970     /// A macro expanding to associated items.
2971     MacCall(P<MacCall>),
2972 }
2973
2974 impl AssocItemKind {
2975     pub fn defaultness(&self) -> Defaultness {
2976         match *self {
2977             Self::Const(defaultness, ..)
2978             | Self::Fn(box Fn { defaultness, .. })
2979             | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
2980             Self::MacCall(..) => Defaultness::Final,
2981         }
2982     }
2983 }
2984
2985 impl From<AssocItemKind> for ItemKind {
2986     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2987         match assoc_item_kind {
2988             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2989             AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2990             AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2991             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2992         }
2993     }
2994 }
2995
2996 impl TryFrom<ItemKind> for AssocItemKind {
2997     type Error = ItemKind;
2998
2999     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
3000         Ok(match item_kind {
3001             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
3002             ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
3003             ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
3004             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
3005             _ => return Err(item_kind),
3006         })
3007     }
3008 }
3009
3010 /// An item in `extern` block.
3011 #[derive(Clone, Encodable, Decodable, Debug)]
3012 pub enum ForeignItemKind {
3013     /// A foreign static item (`static FOO: u8`).
3014     Static(P<Ty>, Mutability, Option<P<Expr>>),
3015     /// An foreign function.
3016     Fn(Box<Fn>),
3017     /// An foreign type.
3018     TyAlias(Box<TyAlias>),
3019     /// A macro expanding to foreign items.
3020     MacCall(P<MacCall>),
3021 }
3022
3023 impl From<ForeignItemKind> for ItemKind {
3024     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3025         match foreign_item_kind {
3026             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3027             ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3028             ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3029             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3030         }
3031     }
3032 }
3033
3034 impl TryFrom<ItemKind> for ForeignItemKind {
3035     type Error = ItemKind;
3036
3037     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3038         Ok(match item_kind {
3039             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3040             ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3041             ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3042             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3043             _ => return Err(item_kind),
3044         })
3045     }
3046 }
3047
3048 pub type ForeignItem = Item<ForeignItemKind>;
3049
3050 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3051 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3052 mod size_asserts {
3053     use super::*;
3054     use rustc_data_structures::static_assert_size;
3055     // tidy-alphabetical-start
3056     static_assert_size!(AssocItem, 104);
3057     static_assert_size!(AssocItemKind, 32);
3058     static_assert_size!(Attribute, 32);
3059     static_assert_size!(Block, 48);
3060     static_assert_size!(Expr, 72);
3061     static_assert_size!(ExprKind, 40);
3062     static_assert_size!(Fn, 184);
3063     static_assert_size!(ForeignItem, 96);
3064     static_assert_size!(ForeignItemKind, 24);
3065     static_assert_size!(GenericArg, 24);
3066     static_assert_size!(GenericBound, 72);
3067     static_assert_size!(Generics, 72);
3068     static_assert_size!(Impl, 184);
3069     static_assert_size!(Item, 184);
3070     static_assert_size!(ItemKind, 112);
3071     static_assert_size!(Lit, 48);
3072     static_assert_size!(LitKind, 24);
3073     static_assert_size!(Local, 72);
3074     static_assert_size!(Param, 40);
3075     static_assert_size!(Pat, 88);
3076     static_assert_size!(Path, 24);
3077     static_assert_size!(PathSegment, 24);
3078     static_assert_size!(PatKind, 64);
3079     static_assert_size!(Stmt, 32);
3080     static_assert_size!(StmtKind, 16);
3081     static_assert_size!(Ty, 64);
3082     static_assert_size!(TyKind, 40);
3083     // tidy-alphabetical-end
3084 }