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