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