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