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