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