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