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