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