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