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