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