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