]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/ast.rs
Rollup merge of #100462 - zohnannor:master, r=thomcc
[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
2064             && let [segment] = &segments[..]
2065             && segment.args.is_none()
2066         {
2067             Some(segment.ident.name)
2068         } else {
2069             None
2070         }
2071     }
2072 }
2073
2074 /// Syntax used to declare a trait object.
2075 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2076 pub enum TraitObjectSyntax {
2077     Dyn,
2078     DynStar,
2079     None,
2080 }
2081
2082 /// Inline assembly operand explicit register or register class.
2083 ///
2084 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2085 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2086 pub enum InlineAsmRegOrRegClass {
2087     Reg(Symbol),
2088     RegClass(Symbol),
2089 }
2090
2091 bitflags::bitflags! {
2092     #[derive(Encodable, Decodable, HashStable_Generic)]
2093     pub struct InlineAsmOptions: u16 {
2094         const PURE            = 1 << 0;
2095         const NOMEM           = 1 << 1;
2096         const READONLY        = 1 << 2;
2097         const PRESERVES_FLAGS = 1 << 3;
2098         const NORETURN        = 1 << 4;
2099         const NOSTACK         = 1 << 5;
2100         const ATT_SYNTAX      = 1 << 6;
2101         const RAW             = 1 << 7;
2102         const MAY_UNWIND      = 1 << 8;
2103     }
2104 }
2105
2106 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2107 pub enum InlineAsmTemplatePiece {
2108     String(String),
2109     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2110 }
2111
2112 impl fmt::Display for InlineAsmTemplatePiece {
2113     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2114         match self {
2115             Self::String(s) => {
2116                 for c in s.chars() {
2117                     match c {
2118                         '{' => f.write_str("{{")?,
2119                         '}' => f.write_str("}}")?,
2120                         _ => c.fmt(f)?,
2121                     }
2122                 }
2123                 Ok(())
2124             }
2125             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2126                 write!(f, "{{{}:{}}}", operand_idx, modifier)
2127             }
2128             Self::Placeholder { operand_idx, modifier: None, .. } => {
2129                 write!(f, "{{{}}}", operand_idx)
2130             }
2131         }
2132     }
2133 }
2134
2135 impl InlineAsmTemplatePiece {
2136     /// Rebuilds the asm template string from its pieces.
2137     pub fn to_string(s: &[Self]) -> String {
2138         use fmt::Write;
2139         let mut out = String::new();
2140         for p in s.iter() {
2141             let _ = write!(out, "{}", p);
2142         }
2143         out
2144     }
2145 }
2146
2147 /// Inline assembly symbol operands get their own AST node that is somewhat
2148 /// similar to `AnonConst`.
2149 ///
2150 /// The main difference is that we specifically don't assign it `DefId` in
2151 /// `DefCollector`. Instead this is deferred until AST lowering where we
2152 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2153 /// depending on what the path resolves to.
2154 #[derive(Clone, Encodable, Decodable, Debug)]
2155 pub struct InlineAsmSym {
2156     pub id: NodeId,
2157     pub qself: Option<QSelf>,
2158     pub path: Path,
2159 }
2160
2161 /// Inline assembly operand.
2162 ///
2163 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2164 #[derive(Clone, Encodable, Decodable, Debug)]
2165 pub enum InlineAsmOperand {
2166     In {
2167         reg: InlineAsmRegOrRegClass,
2168         expr: P<Expr>,
2169     },
2170     Out {
2171         reg: InlineAsmRegOrRegClass,
2172         late: bool,
2173         expr: Option<P<Expr>>,
2174     },
2175     InOut {
2176         reg: InlineAsmRegOrRegClass,
2177         late: bool,
2178         expr: P<Expr>,
2179     },
2180     SplitInOut {
2181         reg: InlineAsmRegOrRegClass,
2182         late: bool,
2183         in_expr: P<Expr>,
2184         out_expr: Option<P<Expr>>,
2185     },
2186     Const {
2187         anon_const: AnonConst,
2188     },
2189     Sym {
2190         sym: InlineAsmSym,
2191     },
2192 }
2193
2194 /// Inline assembly.
2195 ///
2196 /// E.g., `asm!("NOP");`.
2197 #[derive(Clone, Encodable, Decodable, Debug)]
2198 pub struct InlineAsm {
2199     pub template: Vec<InlineAsmTemplatePiece>,
2200     pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2201     pub operands: Vec<(InlineAsmOperand, Span)>,
2202     pub clobber_abis: Vec<(Symbol, Span)>,
2203     pub options: InlineAsmOptions,
2204     pub line_spans: Vec<Span>,
2205 }
2206
2207 /// A parameter in a function header.
2208 ///
2209 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2210 #[derive(Clone, Encodable, Decodable, Debug)]
2211 pub struct Param {
2212     pub attrs: AttrVec,
2213     pub ty: P<Ty>,
2214     pub pat: P<Pat>,
2215     pub id: NodeId,
2216     pub span: Span,
2217     pub is_placeholder: bool,
2218 }
2219
2220 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2221 ///
2222 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2223 #[derive(Clone, Encodable, Decodable, Debug)]
2224 pub enum SelfKind {
2225     /// `self`, `mut self`
2226     Value(Mutability),
2227     /// `&'lt self`, `&'lt mut self`
2228     Region(Option<Lifetime>, Mutability),
2229     /// `self: TYPE`, `mut self: TYPE`
2230     Explicit(P<Ty>, Mutability),
2231 }
2232
2233 pub type ExplicitSelf = Spanned<SelfKind>;
2234
2235 impl Param {
2236     /// Attempts to cast parameter to `ExplicitSelf`.
2237     pub fn to_self(&self) -> Option<ExplicitSelf> {
2238         if let PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), ident, _) = self.pat.kind {
2239             if ident.name == kw::SelfLower {
2240                 return match self.ty.kind {
2241                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2242                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2243                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2244                     }
2245                     _ => Some(respan(
2246                         self.pat.span.to(self.ty.span),
2247                         SelfKind::Explicit(self.ty.clone(), mutbl),
2248                     )),
2249                 };
2250             }
2251         }
2252         None
2253     }
2254
2255     /// Returns `true` if parameter is `self`.
2256     pub fn is_self(&self) -> bool {
2257         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2258             ident.name == kw::SelfLower
2259         } else {
2260             false
2261         }
2262     }
2263
2264     /// Builds a `Param` object from `ExplicitSelf`.
2265     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2266         let span = eself.span.to(eself_ident.span);
2267         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2268         let (mutbl, ty) = match eself.node {
2269             SelfKind::Explicit(ty, mutbl) => (mutbl, ty),
2270             SelfKind::Value(mutbl) => (mutbl, infer_ty),
2271             SelfKind::Region(lt, mutbl) => (
2272                 Mutability::Not,
2273                 P(Ty {
2274                     id: DUMMY_NODE_ID,
2275                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2276                     span,
2277                     tokens: None,
2278                 }),
2279             ),
2280         };
2281         Param {
2282             attrs,
2283             pat: P(Pat {
2284                 id: DUMMY_NODE_ID,
2285                 kind: PatKind::Ident(BindingAnnotation(ByRef::No, mutbl), eself_ident, None),
2286                 span,
2287                 tokens: None,
2288             }),
2289             span,
2290             ty,
2291             id: DUMMY_NODE_ID,
2292             is_placeholder: false,
2293         }
2294     }
2295 }
2296
2297 /// A signature (not the body) of a function declaration.
2298 ///
2299 /// E.g., `fn foo(bar: baz)`.
2300 ///
2301 /// Please note that it's different from `FnHeader` structure
2302 /// which contains metadata about function safety, asyncness, constness and ABI.
2303 #[derive(Clone, Encodable, Decodable, Debug)]
2304 pub struct FnDecl {
2305     pub inputs: Vec<Param>,
2306     pub output: FnRetTy,
2307 }
2308
2309 impl FnDecl {
2310     pub fn has_self(&self) -> bool {
2311         self.inputs.get(0).map_or(false, Param::is_self)
2312     }
2313     pub fn c_variadic(&self) -> bool {
2314         self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2315     }
2316 }
2317
2318 /// Is the trait definition an auto trait?
2319 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2320 pub enum IsAuto {
2321     Yes,
2322     No,
2323 }
2324
2325 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2326 #[derive(HashStable_Generic)]
2327 pub enum Unsafe {
2328     Yes(Span),
2329     No,
2330 }
2331
2332 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2333 pub enum Async {
2334     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2335     No,
2336 }
2337
2338 impl Async {
2339     pub fn is_async(self) -> bool {
2340         matches!(self, Async::Yes { .. })
2341     }
2342
2343     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2344     pub fn opt_return_id(self) -> Option<(NodeId, Span)> {
2345         match self {
2346             Async::Yes { return_impl_trait_id, span, .. } => Some((return_impl_trait_id, span)),
2347             Async::No => None,
2348         }
2349     }
2350 }
2351
2352 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2353 #[derive(HashStable_Generic)]
2354 pub enum Const {
2355     Yes(Span),
2356     No,
2357 }
2358
2359 /// Item defaultness.
2360 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2361 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2362 pub enum Defaultness {
2363     Default(Span),
2364     Final,
2365 }
2366
2367 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2368 pub enum ImplPolarity {
2369     /// `impl Trait for Type`
2370     Positive,
2371     /// `impl !Trait for Type`
2372     Negative(Span),
2373 }
2374
2375 impl fmt::Debug for ImplPolarity {
2376     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2377         match *self {
2378             ImplPolarity::Positive => "positive".fmt(f),
2379             ImplPolarity::Negative(_) => "negative".fmt(f),
2380         }
2381     }
2382 }
2383
2384 #[derive(Clone, Encodable, Decodable, Debug)]
2385 pub enum FnRetTy {
2386     /// Returns type is not specified.
2387     ///
2388     /// Functions default to `()` and closures default to inference.
2389     /// Span points to where return type would be inserted.
2390     Default(Span),
2391     /// Everything else.
2392     Ty(P<Ty>),
2393 }
2394
2395 impl FnRetTy {
2396     pub fn span(&self) -> Span {
2397         match *self {
2398             FnRetTy::Default(span) => span,
2399             FnRetTy::Ty(ref ty) => ty.span,
2400         }
2401     }
2402 }
2403
2404 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2405 pub enum Inline {
2406     Yes,
2407     No,
2408 }
2409
2410 /// Module item kind.
2411 #[derive(Clone, Encodable, Decodable, Debug)]
2412 pub enum ModKind {
2413     /// Module with inlined definition `mod foo { ... }`,
2414     /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2415     /// The inner span is from the first token past `{` to the last token until `}`,
2416     /// or from the first to the last token in the loaded file.
2417     Loaded(Vec<P<Item>>, Inline, ModSpans),
2418     /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2419     Unloaded,
2420 }
2421
2422 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2423 pub struct ModSpans {
2424     /// `inner_span` covers the body of the module; for a file module, its the whole file.
2425     /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2426     pub inner_span: Span,
2427     pub inject_use_span: Span,
2428 }
2429
2430 impl Default for ModSpans {
2431     fn default() -> ModSpans {
2432         ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2433     }
2434 }
2435
2436 /// Foreign module declaration.
2437 ///
2438 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2439 #[derive(Clone, Encodable, Decodable, Debug)]
2440 pub struct ForeignMod {
2441     /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2442     /// semantically by Rust.
2443     pub unsafety: Unsafe,
2444     pub abi: Option<StrLit>,
2445     pub items: Vec<P<ForeignItem>>,
2446 }
2447
2448 #[derive(Clone, Encodable, Decodable, Debug)]
2449 pub struct EnumDef {
2450     pub variants: Vec<Variant>,
2451 }
2452 /// Enum variant.
2453 #[derive(Clone, Encodable, Decodable, Debug)]
2454 pub struct Variant {
2455     /// Attributes of the variant.
2456     pub attrs: AttrVec,
2457     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2458     pub id: NodeId,
2459     /// Span
2460     pub span: Span,
2461     /// The visibility of the variant. Syntactically accepted but not semantically.
2462     pub vis: Visibility,
2463     /// Name of the variant.
2464     pub ident: Ident,
2465
2466     /// Fields and constructor id of the variant.
2467     pub data: VariantData,
2468     /// Explicit discriminant, e.g., `Foo = 1`.
2469     pub disr_expr: Option<AnonConst>,
2470     /// Is a macro placeholder
2471     pub is_placeholder: bool,
2472 }
2473
2474 /// Part of `use` item to the right of its prefix.
2475 #[derive(Clone, Encodable, Decodable, Debug)]
2476 pub enum UseTreeKind {
2477     /// `use prefix` or `use prefix as rename`
2478     ///
2479     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2480     /// namespace.
2481     Simple(Option<Ident>, NodeId, NodeId),
2482     /// `use prefix::{...}`
2483     Nested(Vec<(UseTree, NodeId)>),
2484     /// `use prefix::*`
2485     Glob,
2486 }
2487
2488 /// A tree of paths sharing common prefixes.
2489 /// Used in `use` items both at top-level and inside of braces in import groups.
2490 #[derive(Clone, Encodable, Decodable, Debug)]
2491 pub struct UseTree {
2492     pub prefix: Path,
2493     pub kind: UseTreeKind,
2494     pub span: Span,
2495 }
2496
2497 impl UseTree {
2498     pub fn ident(&self) -> Ident {
2499         match self.kind {
2500             UseTreeKind::Simple(Some(rename), ..) => rename,
2501             UseTreeKind::Simple(None, ..) => {
2502                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2503             }
2504             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2505         }
2506     }
2507 }
2508
2509 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2510 /// are contained as statements within items. These two cases need to be
2511 /// distinguished for pretty-printing.
2512 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2513 pub enum AttrStyle {
2514     Outer,
2515     Inner,
2516 }
2517
2518 rustc_index::newtype_index! {
2519     pub struct AttrId {
2520         ENCODABLE = custom
2521         DEBUG_FORMAT = "AttrId({})"
2522     }
2523 }
2524
2525 impl<S: Encoder> Encodable<S> for AttrId {
2526     fn encode(&self, _s: &mut S) {}
2527 }
2528
2529 impl<D: Decoder> Decodable<D> for AttrId {
2530     default fn decode(_: &mut D) -> AttrId {
2531         panic!("cannot decode `AttrId` with `{}`", std::any::type_name::<D>());
2532     }
2533 }
2534
2535 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2536 pub struct AttrItem {
2537     pub path: Path,
2538     pub args: MacArgs,
2539     pub tokens: Option<LazyAttrTokenStream>,
2540 }
2541
2542 /// A list of attributes.
2543 pub type AttrVec = ThinVec<Attribute>;
2544
2545 /// Metadata associated with an item.
2546 #[derive(Clone, Encodable, Decodable, Debug)]
2547 pub struct Attribute {
2548     pub kind: AttrKind,
2549     pub id: AttrId,
2550     /// Denotes if the attribute decorates the following construct (outer)
2551     /// or the construct this attribute is contained within (inner).
2552     pub style: AttrStyle,
2553     pub span: Span,
2554 }
2555
2556 #[derive(Clone, Encodable, Decodable, Debug)]
2557 pub struct NormalAttr {
2558     pub item: AttrItem,
2559     pub tokens: Option<LazyAttrTokenStream>,
2560 }
2561
2562 #[derive(Clone, Encodable, Decodable, Debug)]
2563 pub enum AttrKind {
2564     /// A normal attribute.
2565     Normal(P<NormalAttr>),
2566
2567     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2568     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2569     /// variant (which is much less compact and thus more expensive).
2570     DocComment(CommentKind, Symbol),
2571 }
2572
2573 /// `TraitRef`s appear in impls.
2574 ///
2575 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2576 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2577 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2578 /// same as the impl's `NodeId`).
2579 #[derive(Clone, Encodable, Decodable, Debug)]
2580 pub struct TraitRef {
2581     pub path: Path,
2582     pub ref_id: NodeId,
2583 }
2584
2585 #[derive(Clone, Encodable, Decodable, Debug)]
2586 pub struct PolyTraitRef {
2587     /// The `'a` in `for<'a> Foo<&'a T>`.
2588     pub bound_generic_params: Vec<GenericParam>,
2589
2590     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2591     pub trait_ref: TraitRef,
2592
2593     pub span: Span,
2594 }
2595
2596 impl PolyTraitRef {
2597     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2598         PolyTraitRef {
2599             bound_generic_params: generic_params,
2600             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2601             span,
2602         }
2603     }
2604 }
2605
2606 #[derive(Clone, Encodable, Decodable, Debug)]
2607 pub struct Visibility {
2608     pub kind: VisibilityKind,
2609     pub span: Span,
2610     pub tokens: Option<LazyAttrTokenStream>,
2611 }
2612
2613 #[derive(Clone, Encodable, Decodable, Debug)]
2614 pub enum VisibilityKind {
2615     Public,
2616     Restricted { path: P<Path>, id: NodeId, shorthand: bool },
2617     Inherited,
2618 }
2619
2620 impl VisibilityKind {
2621     pub fn is_pub(&self) -> bool {
2622         matches!(self, VisibilityKind::Public)
2623     }
2624 }
2625
2626 /// Field definition in a struct, variant or union.
2627 ///
2628 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2629 #[derive(Clone, Encodable, Decodable, Debug)]
2630 pub struct FieldDef {
2631     pub attrs: AttrVec,
2632     pub id: NodeId,
2633     pub span: Span,
2634     pub vis: Visibility,
2635     pub ident: Option<Ident>,
2636
2637     pub ty: P<Ty>,
2638     pub is_placeholder: bool,
2639 }
2640
2641 /// Fields and constructor ids of enum variants and structs.
2642 #[derive(Clone, Encodable, Decodable, Debug)]
2643 pub enum VariantData {
2644     /// Struct variant.
2645     ///
2646     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2647     Struct(Vec<FieldDef>, bool),
2648     /// Tuple variant.
2649     ///
2650     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2651     Tuple(Vec<FieldDef>, NodeId),
2652     /// Unit variant.
2653     ///
2654     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2655     Unit(NodeId),
2656 }
2657
2658 impl VariantData {
2659     /// Return the fields of this variant.
2660     pub fn fields(&self) -> &[FieldDef] {
2661         match *self {
2662             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2663             _ => &[],
2664         }
2665     }
2666
2667     /// Return the `NodeId` of this variant's constructor, if it has one.
2668     pub fn ctor_id(&self) -> Option<NodeId> {
2669         match *self {
2670             VariantData::Struct(..) => None,
2671             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2672         }
2673     }
2674 }
2675
2676 /// An item definition.
2677 #[derive(Clone, Encodable, Decodable, Debug)]
2678 pub struct Item<K = ItemKind> {
2679     pub attrs: AttrVec,
2680     pub id: NodeId,
2681     pub span: Span,
2682     pub vis: Visibility,
2683     /// The name of the item.
2684     /// It might be a dummy name in case of anonymous items.
2685     pub ident: Ident,
2686
2687     pub kind: K,
2688
2689     /// Original tokens this item was parsed from. This isn't necessarily
2690     /// available for all items, although over time more and more items should
2691     /// have this be `Some`. Right now this is primarily used for procedural
2692     /// macros, notably custom attributes.
2693     ///
2694     /// Note that the tokens here do not include the outer attributes, but will
2695     /// include inner attributes.
2696     pub tokens: Option<LazyAttrTokenStream>,
2697 }
2698
2699 impl Item {
2700     /// Return the span that encompasses the attributes.
2701     pub fn span_with_attributes(&self) -> Span {
2702         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2703     }
2704 }
2705
2706 /// `extern` qualifier on a function item or function type.
2707 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2708 pub enum Extern {
2709     None,
2710     Implicit(Span),
2711     Explicit(StrLit, Span),
2712 }
2713
2714 impl Extern {
2715     pub fn from_abi(abi: Option<StrLit>, span: Span) -> Extern {
2716         match abi {
2717             Some(name) => Extern::Explicit(name, span),
2718             None => Extern::Implicit(span),
2719         }
2720     }
2721 }
2722
2723 /// A function header.
2724 ///
2725 /// All the information between the visibility and the name of the function is
2726 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2727 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2728 pub struct FnHeader {
2729     pub unsafety: Unsafe,
2730     pub asyncness: Async,
2731     pub constness: Const,
2732     pub ext: Extern,
2733 }
2734
2735 impl FnHeader {
2736     /// Does this function header have any qualifiers or is it empty?
2737     pub fn has_qualifiers(&self) -> bool {
2738         let Self { unsafety, asyncness, constness, ext } = self;
2739         matches!(unsafety, Unsafe::Yes(_))
2740             || asyncness.is_async()
2741             || matches!(constness, Const::Yes(_))
2742             || !matches!(ext, Extern::None)
2743     }
2744 }
2745
2746 impl Default for FnHeader {
2747     fn default() -> FnHeader {
2748         FnHeader {
2749             unsafety: Unsafe::No,
2750             asyncness: Async::No,
2751             constness: Const::No,
2752             ext: Extern::None,
2753         }
2754     }
2755 }
2756
2757 #[derive(Clone, Encodable, Decodable, Debug)]
2758 pub struct Trait {
2759     pub unsafety: Unsafe,
2760     pub is_auto: IsAuto,
2761     pub generics: Generics,
2762     pub bounds: GenericBounds,
2763     pub items: Vec<P<AssocItem>>,
2764 }
2765
2766 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2767 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2768 /// are two locations for where clause on type aliases, but their predicates
2769 /// are concatenated together.
2770 ///
2771 /// Take this example:
2772 /// ```ignore (only-for-syntax-highlight)
2773 /// trait Foo {
2774 ///   type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2775 /// }
2776 /// impl Foo for () {
2777 ///   type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2778 ///   //                 ^^^^^^^^^^^^^^ first where clause
2779 ///   //                                     ^^^^^^^^^^^^^^ second where clause
2780 /// }
2781 /// ```
2782 ///
2783 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2784 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2785 pub struct TyAliasWhereClause(pub bool, pub Span);
2786
2787 #[derive(Clone, Encodable, Decodable, Debug)]
2788 pub struct TyAlias {
2789     pub defaultness: Defaultness,
2790     pub generics: Generics,
2791     /// The span information for the two where clauses (before equals, after equals)
2792     pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2793     /// The index in `generics.where_clause.predicates` that would split into
2794     /// predicates from the where clause before the equals and the predicates
2795     /// from the where clause after the equals
2796     pub where_predicates_split: usize,
2797     pub bounds: GenericBounds,
2798     pub ty: Option<P<Ty>>,
2799 }
2800
2801 #[derive(Clone, Encodable, Decodable, Debug)]
2802 pub struct Impl {
2803     pub defaultness: Defaultness,
2804     pub unsafety: Unsafe,
2805     pub generics: Generics,
2806     pub constness: Const,
2807     pub polarity: ImplPolarity,
2808     /// The trait being implemented, if any.
2809     pub of_trait: Option<TraitRef>,
2810     pub self_ty: P<Ty>,
2811     pub items: Vec<P<AssocItem>>,
2812 }
2813
2814 #[derive(Clone, Encodable, Decodable, Debug)]
2815 pub struct Fn {
2816     pub defaultness: Defaultness,
2817     pub generics: Generics,
2818     pub sig: FnSig,
2819     pub body: Option<P<Block>>,
2820 }
2821
2822 #[derive(Clone, Encodable, Decodable, Debug)]
2823 pub enum ItemKind {
2824     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2825     ///
2826     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2827     ExternCrate(Option<Symbol>),
2828     /// A use declaration item (`use`).
2829     ///
2830     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2831     Use(UseTree),
2832     /// A static item (`static`).
2833     ///
2834     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2835     Static(P<Ty>, Mutability, Option<P<Expr>>),
2836     /// A constant item (`const`).
2837     ///
2838     /// E.g., `const FOO: i32 = 42;`.
2839     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2840     /// A function declaration (`fn`).
2841     ///
2842     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2843     Fn(Box<Fn>),
2844     /// A module declaration (`mod`).
2845     ///
2846     /// E.g., `mod foo;` or `mod foo { .. }`.
2847     /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2848     /// semantically by Rust.
2849     Mod(Unsafe, ModKind),
2850     /// An external module (`extern`).
2851     ///
2852     /// E.g., `extern {}` or `extern "C" {}`.
2853     ForeignMod(ForeignMod),
2854     /// Module-level inline assembly (from `global_asm!()`).
2855     GlobalAsm(Box<InlineAsm>),
2856     /// A type alias (`type`).
2857     ///
2858     /// E.g., `type Foo = Bar<u8>;`.
2859     TyAlias(Box<TyAlias>),
2860     /// An enum definition (`enum`).
2861     ///
2862     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2863     Enum(EnumDef, Generics),
2864     /// A struct definition (`struct`).
2865     ///
2866     /// E.g., `struct Foo<A> { x: A }`.
2867     Struct(VariantData, Generics),
2868     /// A union definition (`union`).
2869     ///
2870     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2871     Union(VariantData, Generics),
2872     /// A trait declaration (`trait`).
2873     ///
2874     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2875     Trait(Box<Trait>),
2876     /// Trait alias
2877     ///
2878     /// E.g., `trait Foo = Bar + Quux;`.
2879     TraitAlias(Generics, GenericBounds),
2880     /// An implementation.
2881     ///
2882     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2883     Impl(Box<Impl>),
2884     /// A macro invocation.
2885     ///
2886     /// E.g., `foo!(..)`.
2887     MacCall(P<MacCall>),
2888
2889     /// A macro definition.
2890     MacroDef(MacroDef),
2891 }
2892
2893 impl ItemKind {
2894     pub fn article(&self) -> &str {
2895         use ItemKind::*;
2896         match self {
2897             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2898             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2899             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2900         }
2901     }
2902
2903     pub fn descr(&self) -> &str {
2904         match self {
2905             ItemKind::ExternCrate(..) => "extern crate",
2906             ItemKind::Use(..) => "`use` import",
2907             ItemKind::Static(..) => "static item",
2908             ItemKind::Const(..) => "constant item",
2909             ItemKind::Fn(..) => "function",
2910             ItemKind::Mod(..) => "module",
2911             ItemKind::ForeignMod(..) => "extern block",
2912             ItemKind::GlobalAsm(..) => "global asm item",
2913             ItemKind::TyAlias(..) => "type alias",
2914             ItemKind::Enum(..) => "enum",
2915             ItemKind::Struct(..) => "struct",
2916             ItemKind::Union(..) => "union",
2917             ItemKind::Trait(..) => "trait",
2918             ItemKind::TraitAlias(..) => "trait alias",
2919             ItemKind::MacCall(..) => "item macro invocation",
2920             ItemKind::MacroDef(..) => "macro definition",
2921             ItemKind::Impl { .. } => "implementation",
2922         }
2923     }
2924
2925     pub fn generics(&self) -> Option<&Generics> {
2926         match self {
2927             Self::Fn(box Fn { generics, .. })
2928             | Self::TyAlias(box TyAlias { generics, .. })
2929             | Self::Enum(_, generics)
2930             | Self::Struct(_, generics)
2931             | Self::Union(_, generics)
2932             | Self::Trait(box Trait { generics, .. })
2933             | Self::TraitAlias(generics, _)
2934             | Self::Impl(box Impl { generics, .. }) => Some(generics),
2935             _ => None,
2936         }
2937     }
2938 }
2939
2940 /// Represents associated items.
2941 /// These include items in `impl` and `trait` definitions.
2942 pub type AssocItem = Item<AssocItemKind>;
2943
2944 /// Represents associated item kinds.
2945 ///
2946 /// The term "provided" in the variants below refers to the item having a default
2947 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2948 /// In an implementation, all items must be provided.
2949 /// The `Option`s below denote the bodies, where `Some(_)`
2950 /// means "provided" and conversely `None` means "required".
2951 #[derive(Clone, Encodable, Decodable, Debug)]
2952 pub enum AssocItemKind {
2953     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2954     /// If `def` is parsed, then the constant is provided, and otherwise required.
2955     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2956     /// An associated function.
2957     Fn(Box<Fn>),
2958     /// An associated type.
2959     Type(Box<TyAlias>),
2960     /// A macro expanding to associated items.
2961     MacCall(P<MacCall>),
2962 }
2963
2964 impl AssocItemKind {
2965     pub fn defaultness(&self) -> Defaultness {
2966         match *self {
2967             Self::Const(defaultness, ..)
2968             | Self::Fn(box Fn { defaultness, .. })
2969             | Self::Type(box TyAlias { defaultness, .. }) => defaultness,
2970             Self::MacCall(..) => Defaultness::Final,
2971         }
2972     }
2973 }
2974
2975 impl From<AssocItemKind> for ItemKind {
2976     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2977         match assoc_item_kind {
2978             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2979             AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2980             AssocItemKind::Type(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2981             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2982         }
2983     }
2984 }
2985
2986 impl TryFrom<ItemKind> for AssocItemKind {
2987     type Error = ItemKind;
2988
2989     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2990         Ok(match item_kind {
2991             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2992             ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2993             ItemKind::TyAlias(ty_kind) => AssocItemKind::Type(ty_kind),
2994             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2995             _ => return Err(item_kind),
2996         })
2997     }
2998 }
2999
3000 /// An item in `extern` block.
3001 #[derive(Clone, Encodable, Decodable, Debug)]
3002 pub enum ForeignItemKind {
3003     /// A foreign static item (`static FOO: u8`).
3004     Static(P<Ty>, Mutability, Option<P<Expr>>),
3005     /// An foreign function.
3006     Fn(Box<Fn>),
3007     /// An foreign type.
3008     TyAlias(Box<TyAlias>),
3009     /// A macro expanding to foreign items.
3010     MacCall(P<MacCall>),
3011 }
3012
3013 impl From<ForeignItemKind> for ItemKind {
3014     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3015         match foreign_item_kind {
3016             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3017             ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3018             ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3019             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3020         }
3021     }
3022 }
3023
3024 impl TryFrom<ItemKind> for ForeignItemKind {
3025     type Error = ItemKind;
3026
3027     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3028         Ok(match item_kind {
3029             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3030             ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3031             ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3032             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3033             _ => return Err(item_kind),
3034         })
3035     }
3036 }
3037
3038 pub type ForeignItem = Item<ForeignItemKind>;
3039
3040 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
3041 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
3042 mod size_asserts {
3043     use super::*;
3044     use rustc_data_structures::static_assert_size;
3045     // tidy-alphabetical-start
3046     static_assert_size!(AssocItem, 104);
3047     static_assert_size!(AssocItemKind, 32);
3048     static_assert_size!(Attribute, 32);
3049     static_assert_size!(Block, 48);
3050     static_assert_size!(Expr, 104);
3051     static_assert_size!(ExprKind, 72);
3052     static_assert_size!(Fn, 184);
3053     static_assert_size!(ForeignItem, 96);
3054     static_assert_size!(ForeignItemKind, 24);
3055     static_assert_size!(GenericArg, 24);
3056     static_assert_size!(GenericBound, 88);
3057     static_assert_size!(Generics, 72);
3058     static_assert_size!(Impl, 200);
3059     static_assert_size!(Item, 184);
3060     static_assert_size!(ItemKind, 112);
3061     static_assert_size!(Lit, 48);
3062     static_assert_size!(LitKind, 24);
3063     static_assert_size!(Local, 72);
3064     static_assert_size!(Param, 40);
3065     static_assert_size!(Pat, 120);
3066     static_assert_size!(Path, 40);
3067     static_assert_size!(PathSegment, 24);
3068     static_assert_size!(PatKind, 96);
3069     static_assert_size!(Stmt, 32);
3070     static_assert_size!(StmtKind, 16);
3071     static_assert_size!(Ty, 96);
3072     static_assert_size!(TyKind, 72);
3073     // tidy-alphabetical-end
3074 }