]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
cf54fd2887af6018b5382da120e4b2581ad33051
[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: FunctionRetTy,
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 normal borrow, `&$expr` or `&mut $expr`.
732     /// The resulting type is either `&'a T` or `&'a mut T`
733     /// where `T = typeof($expr)` and `'a` is some lifetime.
734     Ref,
735     /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
736     /// The resulting type is either `*const T` or `*mut T`
737     /// where `T = typeof($expr)`.
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 associated items.
1607 /// These include items in `impl` and `trait` definitions.
1608 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1609 pub struct AssocItem {
1610     pub attrs: Vec<Attribute>,
1611     pub id: NodeId,
1612     pub span: Span,
1613     pub vis: Visibility,
1614     pub ident: Ident,
1615
1616     pub defaultness: Defaultness,
1617     pub generics: Generics,
1618     pub kind: AssocItemKind,
1619     /// See `Item::tokens` for what this is.
1620     pub tokens: Option<TokenStream>,
1621 }
1622
1623 /// Represents various kinds of content within an `impl`.
1624 ///
1625 /// The term "provided" in the variants below refers to the item having a default
1626 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
1627 /// In an implementation, all items must be provided.
1628 /// The `Option`s below denote the bodies, where `Some(_)`
1629 /// means "provided" and conversely `None` means "required".
1630 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1631 pub enum AssocItemKind  {
1632     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
1633     /// If `def` is parsed, then the associated constant is provided, and otherwise required.
1634     Const(P<Ty>, Option<P<Expr>>),
1635
1636     /// An associated function.
1637     Fn(FnSig, Option<P<Block>>),
1638
1639     /// An associated type.
1640     TyAlias(GenericBounds, Option<P<Ty>>),
1641
1642     /// A macro expanding to an associated item.
1643     Macro(Mac),
1644 }
1645
1646 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1647          RustcEncodable, RustcDecodable, Debug)]
1648 pub enum FloatTy {
1649     F32,
1650     F64,
1651 }
1652
1653 impl FloatTy {
1654     pub fn name_str(self) -> &'static str {
1655         match self {
1656             FloatTy::F32 => "f32",
1657             FloatTy::F64 => "f64",
1658         }
1659     }
1660
1661     pub fn name(self) -> Symbol {
1662         match self {
1663             FloatTy::F32 => sym::f32,
1664             FloatTy::F64 => sym::f64,
1665         }
1666     }
1667
1668     pub fn bit_width(self) -> usize {
1669         match self {
1670             FloatTy::F32 => 32,
1671             FloatTy::F64 => 64,
1672         }
1673     }
1674 }
1675
1676 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1677          RustcEncodable, RustcDecodable, Debug)]
1678 pub enum IntTy {
1679     Isize,
1680     I8,
1681     I16,
1682     I32,
1683     I64,
1684     I128,
1685 }
1686
1687 impl IntTy {
1688     pub fn name_str(&self) -> &'static str {
1689         match *self {
1690             IntTy::Isize => "isize",
1691             IntTy::I8 => "i8",
1692             IntTy::I16 => "i16",
1693             IntTy::I32 => "i32",
1694             IntTy::I64 => "i64",
1695             IntTy::I128 => "i128",
1696         }
1697     }
1698
1699     pub fn name(&self) -> Symbol {
1700         match *self {
1701             IntTy::Isize => sym::isize,
1702             IntTy::I8 => sym::i8,
1703             IntTy::I16 => sym::i16,
1704             IntTy::I32 => sym::i32,
1705             IntTy::I64 => sym::i64,
1706             IntTy::I128 => sym::i128,
1707         }
1708     }
1709
1710     pub fn val_to_string(&self, val: i128) -> String {
1711         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1712         // are parsed as `u128`, so we wouldn't want to print an extra negative
1713         // sign.
1714         format!("{}{}", val as u128, self.name_str())
1715     }
1716
1717     pub fn bit_width(&self) -> Option<usize> {
1718         Some(match *self {
1719             IntTy::Isize => return None,
1720             IntTy::I8 => 8,
1721             IntTy::I16 => 16,
1722             IntTy::I32 => 32,
1723             IntTy::I64 => 64,
1724             IntTy::I128 => 128,
1725         })
1726     }
1727
1728     pub fn normalize(&self, target_width: u32) -> Self {
1729         match self {
1730             IntTy::Isize => match target_width {
1731                 16 => IntTy::I16,
1732                 32 => IntTy::I32,
1733                 64 => IntTy::I64,
1734                 _ => unreachable!(),
1735             },
1736             _ => *self,
1737         }
1738     }
1739 }
1740
1741 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1742          RustcEncodable, RustcDecodable, Copy, Debug)]
1743 pub enum UintTy {
1744     Usize,
1745     U8,
1746     U16,
1747     U32,
1748     U64,
1749     U128,
1750 }
1751
1752 impl UintTy {
1753     pub fn name_str(&self) -> &'static str {
1754         match *self {
1755             UintTy::Usize => "usize",
1756             UintTy::U8 => "u8",
1757             UintTy::U16 => "u16",
1758             UintTy::U32 => "u32",
1759             UintTy::U64 => "u64",
1760             UintTy::U128 => "u128",
1761         }
1762     }
1763
1764     pub fn name(&self) -> Symbol {
1765         match *self {
1766             UintTy::Usize => sym::usize,
1767             UintTy::U8 => sym::u8,
1768             UintTy::U16 => sym::u16,
1769             UintTy::U32 => sym::u32,
1770             UintTy::U64 => sym::u64,
1771             UintTy::U128 => sym::u128,
1772         }
1773     }
1774
1775     pub fn val_to_string(&self, val: u128) -> String {
1776         format!("{}{}", val, self.name_str())
1777     }
1778
1779     pub fn bit_width(&self) -> Option<usize> {
1780         Some(match *self {
1781             UintTy::Usize => return None,
1782             UintTy::U8 => 8,
1783             UintTy::U16 => 16,
1784             UintTy::U32 => 32,
1785             UintTy::U64 => 64,
1786             UintTy::U128 => 128,
1787         })
1788     }
1789
1790     pub fn normalize(&self, target_width: u32) -> Self {
1791         match self {
1792             UintTy::Usize => match target_width {
1793                 16 => UintTy::U16,
1794                 32 => UintTy::U32,
1795                 64 => UintTy::U64,
1796                 _ => unreachable!(),
1797             },
1798             _ => *self,
1799         }
1800     }
1801 }
1802
1803 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1804 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1805 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1806 pub struct AssocTyConstraint {
1807     pub id: NodeId,
1808     pub ident: Ident,
1809     pub kind: AssocTyConstraintKind,
1810     pub span: Span,
1811 }
1812
1813 /// The kinds of an `AssocTyConstraint`.
1814 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1815 pub enum AssocTyConstraintKind {
1816     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1817     Equality {
1818         ty: P<Ty>,
1819     },
1820     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1821     Bound {
1822         bounds: GenericBounds,
1823     },
1824 }
1825
1826 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1827 pub struct Ty {
1828     pub id: NodeId,
1829     pub kind: TyKind,
1830     pub span: Span,
1831 }
1832
1833 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1834 pub struct BareFnTy {
1835     pub unsafety: Unsafety,
1836     pub ext: Extern,
1837     pub generic_params: Vec<GenericParam>,
1838     pub decl: P<FnDecl>,
1839 }
1840
1841 /// The various kinds of type recognized by the compiler.
1842 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1843 pub enum TyKind {
1844     /// A variable-length slice (`[T]`).
1845     Slice(P<Ty>),
1846     /// A fixed length array (`[T; n]`).
1847     Array(P<Ty>, AnonConst),
1848     /// A raw pointer (`*const T` or `*mut T`).
1849     Ptr(MutTy),
1850     /// A reference (`&'a T` or `&'a mut T`).
1851     Rptr(Option<Lifetime>, MutTy),
1852     /// A bare function (e.g., `fn(usize) -> bool`).
1853     BareFn(P<BareFnTy>),
1854     /// The never type (`!`).
1855     Never,
1856     /// A tuple (`(A, B, C, D,...)`).
1857     Tup(Vec<P<Ty>>),
1858     /// A path (`module::module::...::Type`), optionally
1859     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1860     ///
1861     /// Type parameters are stored in the `Path` itself.
1862     Path(Option<QSelf>, Path),
1863     /// A trait object type `Bound1 + Bound2 + Bound3`
1864     /// where `Bound` is a trait or a lifetime.
1865     TraitObject(GenericBounds, TraitObjectSyntax),
1866     /// An `impl Bound1 + Bound2 + Bound3` type
1867     /// where `Bound` is a trait or a lifetime.
1868     ///
1869     /// The `NodeId` exists to prevent lowering from having to
1870     /// generate `NodeId`s on the fly, which would complicate
1871     /// the generation of opaque `type Foo = impl Trait` items significantly.
1872     ImplTrait(NodeId, GenericBounds),
1873     /// No-op; kept solely so that we can pretty-print faithfully.
1874     Paren(P<Ty>),
1875     /// Unused for now.
1876     Typeof(AnonConst),
1877     /// This means the type should be inferred instead of it having been
1878     /// specified. This can appear anywhere in a type.
1879     Infer,
1880     /// Inferred type of a `self` or `&self` argument in a method.
1881     ImplicitSelf,
1882     /// A macro in the type position.
1883     Mac(Mac),
1884     /// Placeholder for a kind that has failed to be defined.
1885     Err,
1886     /// Placeholder for a `va_list`.
1887     CVarArgs,
1888 }
1889
1890 impl TyKind {
1891     pub fn is_implicit_self(&self) -> bool {
1892         if let TyKind::ImplicitSelf = *self {
1893             true
1894         } else {
1895             false
1896         }
1897     }
1898
1899     pub fn is_unit(&self) -> bool {
1900         if let TyKind::Tup(ref tys) = *self {
1901             tys.is_empty()
1902         } else {
1903             false
1904         }
1905     }
1906
1907     /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1908     /// in lowering to avoid making larger changes there and beyond.
1909     pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1910         match self {
1911             Self::ImplTrait(_, bounds) => Some(bounds),
1912             _ => None,
1913         }
1914     }
1915 }
1916
1917 /// Syntax used to declare a trait object.
1918 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1919 pub enum TraitObjectSyntax {
1920     Dyn,
1921     None,
1922 }
1923
1924 /// Inline assembly dialect.
1925 ///
1926 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1927 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1928 pub enum AsmDialect {
1929     Att,
1930     Intel,
1931 }
1932
1933 /// Inline assembly.
1934 ///
1935 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1936 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1937 pub struct InlineAsmOutput {
1938     pub constraint: Symbol,
1939     pub expr: P<Expr>,
1940     pub is_rw: bool,
1941     pub is_indirect: bool,
1942 }
1943
1944 /// Inline assembly.
1945 ///
1946 /// E.g., `asm!("NOP");`.
1947 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1948 pub struct InlineAsm {
1949     pub asm: Symbol,
1950     pub asm_str_style: StrStyle,
1951     pub outputs: Vec<InlineAsmOutput>,
1952     pub inputs: Vec<(Symbol, P<Expr>)>,
1953     pub clobbers: Vec<Symbol>,
1954     pub volatile: bool,
1955     pub alignstack: bool,
1956     pub dialect: AsmDialect,
1957 }
1958
1959 /// A parameter in a function header.
1960 ///
1961 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1962 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1963 pub struct Param {
1964     pub attrs: ThinVec<Attribute>,
1965     pub ty: P<Ty>,
1966     pub pat: P<Pat>,
1967     pub id: NodeId,
1968     pub span: Span,
1969     pub is_placeholder: bool,
1970 }
1971
1972 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1973 ///
1974 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1975 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1976 pub enum SelfKind {
1977     /// `self`, `mut self`
1978     Value(Mutability),
1979     /// `&'lt self`, `&'lt mut self`
1980     Region(Option<Lifetime>, Mutability),
1981     /// `self: TYPE`, `mut self: TYPE`
1982     Explicit(P<Ty>, Mutability),
1983 }
1984
1985 pub type ExplicitSelf = Spanned<SelfKind>;
1986
1987 impl Param {
1988     /// Attempts to cast parameter to `ExplicitSelf`.
1989     pub fn to_self(&self) -> Option<ExplicitSelf> {
1990         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1991             if ident.name == kw::SelfLower {
1992                 return match self.ty.kind {
1993                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1994                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1995                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1996                     }
1997                     _ => Some(respan(
1998                         self.pat.span.to(self.ty.span),
1999                         SelfKind::Explicit(self.ty.clone(), mutbl),
2000                     )),
2001                 };
2002             }
2003         }
2004         None
2005     }
2006
2007     /// Returns `true` if parameter is `self`.
2008     pub fn is_self(&self) -> bool {
2009         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2010             ident.name == kw::SelfLower
2011         } else {
2012             false
2013         }
2014     }
2015
2016     /// Builds a `Param` object from `ExplicitSelf`.
2017     pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2018         let span = eself.span.to(eself_ident.span);
2019         let infer_ty = P(Ty {
2020             id: DUMMY_NODE_ID,
2021             kind: TyKind::ImplicitSelf,
2022             span,
2023         });
2024         let param = |mutbl, ty| Param {
2025             attrs,
2026             pat: P(Pat {
2027                 id: DUMMY_NODE_ID,
2028                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2029                 span,
2030             }),
2031             span,
2032             ty,
2033             id: DUMMY_NODE_ID,
2034             is_placeholder: false
2035         };
2036         match eself.node {
2037             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2038             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2039             SelfKind::Region(lt, mutbl) => param(
2040                 Mutability::Immutable,
2041                 P(Ty {
2042                     id: DUMMY_NODE_ID,
2043                     kind: TyKind::Rptr(
2044                         lt,
2045                         MutTy {
2046                             ty: infer_ty,
2047                             mutbl,
2048                         },
2049                     ),
2050                     span,
2051                 }),
2052             ),
2053         }
2054     }
2055 }
2056
2057 /// A signature (not the body) of a function declaration.
2058 ///
2059 /// E.g., `fn foo(bar: baz)`.
2060 ///
2061 /// Please note that it's different from `FnHeader` structure
2062 /// which contains metadata about function safety, asyncness, constness and ABI.
2063 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2064 pub struct FnDecl {
2065     pub inputs: Vec<Param>,
2066     pub output: FunctionRetTy,
2067 }
2068
2069 impl FnDecl {
2070     pub fn get_self(&self) -> Option<ExplicitSelf> {
2071         self.inputs.get(0).and_then(Param::to_self)
2072     }
2073     pub fn has_self(&self) -> bool {
2074         self.inputs.get(0).map_or(false, Param::is_self)
2075     }
2076     pub fn c_variadic(&self) -> bool {
2077         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2078             TyKind::CVarArgs => true,
2079             _ => false,
2080         })
2081     }
2082 }
2083
2084 /// Is the trait definition an auto trait?
2085 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2086 pub enum IsAuto {
2087     Yes,
2088     No,
2089 }
2090
2091 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2092          RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2093 pub enum Unsafety {
2094     Unsafe,
2095     Normal,
2096 }
2097
2098 impl Unsafety {
2099     pub fn prefix_str(&self) -> &'static str {
2100         match self {
2101             Unsafety::Unsafe => "unsafe ",
2102             Unsafety::Normal => "",
2103         }
2104     }
2105 }
2106
2107 impl fmt::Display for Unsafety {
2108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2109         fmt::Display::fmt(
2110             match *self {
2111                 Unsafety::Normal => "normal",
2112                 Unsafety::Unsafe => "unsafe",
2113             },
2114             f,
2115         )
2116     }
2117 }
2118
2119 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2120 pub enum IsAsync {
2121     Async {
2122         closure_id: NodeId,
2123         return_impl_trait_id: NodeId,
2124     },
2125     NotAsync,
2126 }
2127
2128 impl IsAsync {
2129     pub fn is_async(self) -> bool {
2130         if let IsAsync::Async { .. } = self {
2131             true
2132         } else {
2133             false
2134         }
2135     }
2136
2137     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2138     pub fn opt_return_id(self) -> Option<NodeId> {
2139         match self {
2140             IsAsync::Async {
2141                 return_impl_trait_id,
2142                 ..
2143             } => Some(return_impl_trait_id),
2144             IsAsync::NotAsync => None,
2145         }
2146     }
2147 }
2148
2149 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2150 pub enum Constness {
2151     Const,
2152     NotConst,
2153 }
2154
2155 /// Item defaultness.
2156 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2157 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2158 pub enum Defaultness {
2159     Default,
2160     Final,
2161 }
2162
2163 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2164 pub enum ImplPolarity {
2165     /// `impl Trait for Type`
2166     Positive,
2167     /// `impl !Trait for Type`
2168     Negative,
2169 }
2170
2171 impl fmt::Debug for ImplPolarity {
2172     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2173         match *self {
2174             ImplPolarity::Positive => "positive".fmt(f),
2175             ImplPolarity::Negative => "negative".fmt(f),
2176         }
2177     }
2178 }
2179
2180 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2181 pub enum FunctionRetTy { // FIXME(Centril): Rename to `FnRetTy` and in HIR also.
2182     /// Returns type is not specified.
2183     ///
2184     /// Functions default to `()` and closures default to inference.
2185     /// Span points to where return type would be inserted.
2186     Default(Span),
2187     /// Everything else.
2188     Ty(P<Ty>),
2189 }
2190
2191 impl FunctionRetTy {
2192     pub fn span(&self) -> Span {
2193         match *self {
2194             FunctionRetTy::Default(span) => span,
2195             FunctionRetTy::Ty(ref ty) => ty.span,
2196         }
2197     }
2198 }
2199
2200 /// Module declaration.
2201 ///
2202 /// E.g., `mod foo;` or `mod foo { .. }`.
2203 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2204 pub struct Mod {
2205     /// A span from the first token past `{` to the last token until `}`.
2206     /// For `mod foo;`, the inner span ranges from the first token
2207     /// to the last token in the external file.
2208     pub inner: Span,
2209     pub items: Vec<P<Item>>,
2210     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2211     pub inline: bool,
2212 }
2213
2214 /// Foreign module declaration.
2215 ///
2216 /// E.g., `extern { .. }` or `extern C { .. }`.
2217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2218 pub struct ForeignMod {
2219     pub abi: Option<StrLit>,
2220     pub items: Vec<ForeignItem>,
2221 }
2222
2223 /// Global inline assembly.
2224 ///
2225 /// Also known as "module-level assembly" or "file-scoped assembly".
2226 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2227 pub struct GlobalAsm {
2228     pub asm: Symbol,
2229 }
2230
2231 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2232 pub struct EnumDef {
2233     pub variants: Vec<Variant>,
2234 }
2235 /// Enum variant.
2236 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2237 pub struct Variant {
2238     /// Attributes of the variant.
2239     pub attrs: Vec<Attribute>,
2240     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2241     pub id: NodeId,
2242     /// Span
2243     pub span: Span,
2244     /// The visibility of the variant. Syntactically accepted but not semantically.
2245     pub vis: Visibility,
2246     /// Name of the variant.
2247     pub ident: Ident,
2248
2249     /// Fields and constructor id of the variant.
2250     pub data: VariantData,
2251     /// Explicit discriminant, e.g., `Foo = 1`.
2252     pub disr_expr: Option<AnonConst>,
2253     /// Is a macro placeholder
2254     pub is_placeholder: bool,
2255 }
2256
2257 /// Part of `use` item to the right of its prefix.
2258 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2259 pub enum UseTreeKind {
2260     /// `use prefix` or `use prefix as rename`
2261     ///
2262     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2263     /// namespace.
2264     Simple(Option<Ident>, NodeId, NodeId),
2265     /// `use prefix::{...}`
2266     Nested(Vec<(UseTree, NodeId)>),
2267     /// `use prefix::*`
2268     Glob,
2269 }
2270
2271 /// A tree of paths sharing common prefixes.
2272 /// Used in `use` items both at top-level and inside of braces in import groups.
2273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2274 pub struct UseTree {
2275     pub prefix: Path,
2276     pub kind: UseTreeKind,
2277     pub span: Span,
2278 }
2279
2280 impl UseTree {
2281     pub fn ident(&self) -> Ident {
2282         match self.kind {
2283             UseTreeKind::Simple(Some(rename), ..) => rename,
2284             UseTreeKind::Simple(None, ..) => {
2285                 self.prefix
2286                     .segments
2287                     .last()
2288                     .expect("empty prefix in a simple import")
2289                     .ident
2290             }
2291             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2292         }
2293     }
2294 }
2295
2296 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2297 /// are contained as statements within items. These two cases need to be
2298 /// distinguished for pretty-printing.
2299 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2300 pub enum AttrStyle {
2301     Outer,
2302     Inner,
2303 }
2304
2305 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2306 pub struct AttrId(pub usize);
2307
2308 impl Idx for AttrId {
2309     fn new(idx: usize) -> Self {
2310         AttrId(idx)
2311     }
2312     fn index(self) -> usize {
2313         self.0
2314     }
2315 }
2316
2317 impl rustc_serialize::Encodable for AttrId {
2318     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2319         s.emit_unit()
2320     }
2321 }
2322
2323 impl rustc_serialize::Decodable for AttrId {
2324     fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2325         d.read_nil().map(|_| crate::attr::mk_attr_id())
2326     }
2327 }
2328
2329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2330 pub struct AttrItem {
2331     pub path: Path,
2332     pub args: MacArgs,
2333 }
2334
2335 /// Metadata associated with an item.
2336 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2337 pub struct Attribute {
2338     pub kind: AttrKind,
2339     pub id: AttrId,
2340     /// Denotes if the attribute decorates the following construct (outer)
2341     /// or the construct this attribute is contained within (inner).
2342     pub style: AttrStyle,
2343     pub span: Span,
2344 }
2345
2346 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2347 pub enum AttrKind {
2348     /// A normal attribute.
2349     Normal(AttrItem),
2350
2351     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2352     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2353     /// variant (which is much less compact and thus more expensive).
2354     ///
2355     /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2356     /// for this variant, but this may change in the future.
2357     /// ```
2358     DocComment(Symbol),
2359 }
2360
2361 /// `TraitRef`s appear in impls.
2362 ///
2363 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2364 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2365 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2366 /// same as the impl's `NodeId`).
2367 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2368 pub struct TraitRef {
2369     pub path: Path,
2370     pub ref_id: NodeId,
2371 }
2372
2373 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2374 pub struct PolyTraitRef {
2375     /// The `'a` in `<'a> Foo<&'a T>`.
2376     pub bound_generic_params: Vec<GenericParam>,
2377
2378     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2379     pub trait_ref: TraitRef,
2380
2381     pub span: Span,
2382 }
2383
2384 impl PolyTraitRef {
2385     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2386         PolyTraitRef {
2387             bound_generic_params: generic_params,
2388             trait_ref: TraitRef {
2389                 path,
2390                 ref_id: DUMMY_NODE_ID,
2391             },
2392             span,
2393         }
2394     }
2395 }
2396
2397 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2398 pub enum CrateSugar {
2399     /// Source is `pub(crate)`.
2400     PubCrate,
2401
2402     /// Source is (just) `crate`.
2403     JustCrate,
2404 }
2405
2406 pub type Visibility = Spanned<VisibilityKind>;
2407
2408 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2409 pub enum VisibilityKind {
2410     Public,
2411     Crate(CrateSugar),
2412     Restricted { path: P<Path>, id: NodeId },
2413     Inherited,
2414 }
2415
2416 impl VisibilityKind {
2417     pub fn is_pub(&self) -> bool {
2418         if let VisibilityKind::Public = *self {
2419             true
2420         } else {
2421             false
2422         }
2423     }
2424 }
2425
2426 /// Field of a struct.
2427 ///
2428 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2429 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2430 pub struct StructField {
2431     pub attrs: Vec<Attribute>,
2432     pub id: NodeId,
2433     pub span: Span,
2434     pub vis: Visibility,
2435     pub ident: Option<Ident>,
2436
2437     pub ty: P<Ty>,
2438     pub is_placeholder: bool,
2439 }
2440
2441 /// Fields and constructor ids of enum variants and structs.
2442 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2443 pub enum VariantData {
2444     /// Struct variant.
2445     ///
2446     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2447     Struct(Vec<StructField>, bool),
2448     /// Tuple variant.
2449     ///
2450     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2451     Tuple(Vec<StructField>, NodeId),
2452     /// Unit variant.
2453     ///
2454     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2455     Unit(NodeId),
2456 }
2457
2458 impl VariantData {
2459     /// Return the fields of this variant.
2460     pub fn fields(&self) -> &[StructField] {
2461         match *self {
2462             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2463             _ => &[],
2464         }
2465     }
2466
2467     /// Return the `NodeId` of this variant's constructor, if it has one.
2468     pub fn ctor_id(&self) -> Option<NodeId> {
2469         match *self {
2470             VariantData::Struct(..) => None,
2471             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2472         }
2473     }
2474 }
2475
2476 /// An item.
2477 ///
2478 /// The name might be a dummy name in case of anonymous items.
2479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2480 pub struct Item<K = ItemKind> {
2481     pub attrs: Vec<Attribute>,
2482     pub id: NodeId,
2483     pub span: Span,
2484     pub vis: Visibility,
2485     pub ident: Ident,
2486
2487     pub kind: K,
2488
2489     /// Original tokens this item was parsed from. This isn't necessarily
2490     /// available for all items, although over time more and more items should
2491     /// have this be `Some`. Right now this is primarily used for procedural
2492     /// macros, notably custom attributes.
2493     ///
2494     /// Note that the tokens here do not include the outer attributes, but will
2495     /// include inner attributes.
2496     pub tokens: Option<TokenStream>,
2497 }
2498
2499 impl Item {
2500     /// Return the span that encompasses the attributes.
2501     pub fn span_with_attributes(&self) -> Span {
2502         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2503     }
2504 }
2505
2506 /// `extern` qualifier on a function item or function type.
2507 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2508 pub enum Extern {
2509     None,
2510     Implicit,
2511     Explicit(StrLit),
2512 }
2513
2514 impl Extern {
2515     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2516         abi.map_or(Extern::Implicit, Extern::Explicit)
2517     }
2518 }
2519
2520 /// A function header.
2521 ///
2522 /// All the information between the visibility and the name of the function is
2523 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2524 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2525 pub struct FnHeader {
2526     pub unsafety: Unsafety,
2527     pub asyncness: Spanned<IsAsync>,
2528     pub constness: Spanned<Constness>,
2529     pub ext: Extern,
2530 }
2531
2532 impl Default for FnHeader {
2533     fn default() -> FnHeader {
2534         FnHeader {
2535             unsafety: Unsafety::Normal,
2536             asyncness: dummy_spanned(IsAsync::NotAsync),
2537             constness: dummy_spanned(Constness::NotConst),
2538             ext: Extern::None,
2539         }
2540     }
2541 }
2542
2543 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2544 pub enum ItemKind {
2545     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2546     ///
2547     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2548     ExternCrate(Option<Name>),
2549     /// A use declaration item (`use`).
2550     ///
2551     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2552     Use(P<UseTree>),
2553     /// A static item (`static`).
2554     ///
2555     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2556     Static(P<Ty>, Mutability, P<Expr>),
2557     /// A constant item (`const`).
2558     ///
2559     /// E.g., `const FOO: i32 = 42;`.
2560     Const(P<Ty>, P<Expr>),
2561     /// A function declaration (`fn`).
2562     ///
2563     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2564     Fn(FnSig, Generics, P<Block>),
2565     /// A module declaration (`mod`).
2566     ///
2567     /// E.g., `mod foo;` or `mod foo { .. }`.
2568     Mod(Mod),
2569     /// An external module (`extern`).
2570     ///
2571     /// E.g., `extern {}` or `extern "C" {}`.
2572     ForeignMod(ForeignMod),
2573     /// Module-level inline assembly (from `global_asm!()`).
2574     GlobalAsm(P<GlobalAsm>),
2575     /// A type alias (`type`).
2576     ///
2577     /// E.g., `type Foo = Bar<u8>;`.
2578     TyAlias(P<Ty>, Generics),
2579     /// An enum definition (`enum`).
2580     ///
2581     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2582     Enum(EnumDef, Generics),
2583     /// A struct definition (`struct`).
2584     ///
2585     /// E.g., `struct Foo<A> { x: A }`.
2586     Struct(VariantData, Generics),
2587     /// A union definition (`union`).
2588     ///
2589     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2590     Union(VariantData, Generics),
2591     /// A trait declaration (`trait`).
2592     ///
2593     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2594     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<AssocItem>),
2595     /// Trait alias
2596     ///
2597     /// E.g., `trait Foo = Bar + Quux;`.
2598     TraitAlias(Generics, GenericBounds),
2599     /// An implementation.
2600     ///
2601     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2602     Impl(
2603         Unsafety,
2604         ImplPolarity,
2605         Defaultness,
2606         Generics,
2607         Option<TraitRef>, // (optional) trait this impl implements
2608         P<Ty>,            // self
2609         Vec<AssocItem>,
2610     ),
2611     /// A macro invocation.
2612     ///
2613     /// E.g., `foo!(..)`.
2614     Mac(Mac),
2615
2616     /// A macro definition.
2617     MacroDef(MacroDef),
2618 }
2619
2620 impl ItemKind {
2621     pub fn descriptive_variant(&self) -> &str {
2622         match *self {
2623             ItemKind::ExternCrate(..) => "extern crate",
2624             ItemKind::Use(..) => "use",
2625             ItemKind::Static(..) => "static item",
2626             ItemKind::Const(..) => "constant item",
2627             ItemKind::Fn(..) => "function",
2628             ItemKind::Mod(..) => "module",
2629             ItemKind::ForeignMod(..) => "foreign module",
2630             ItemKind::GlobalAsm(..) => "global asm",
2631             ItemKind::TyAlias(..) => "type alias",
2632             ItemKind::Enum(..) => "enum",
2633             ItemKind::Struct(..) => "struct",
2634             ItemKind::Union(..) => "union",
2635             ItemKind::Trait(..) => "trait",
2636             ItemKind::TraitAlias(..) => "trait alias",
2637             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2638         }
2639     }
2640 }
2641
2642 pub type ForeignItem = Item<ForeignItemKind>;
2643
2644 /// An item within an `extern` block.
2645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2646 pub enum ForeignItemKind {
2647     /// A foreign function.
2648     Fn(P<FnDecl>, Generics),
2649     /// A foreign static item (`static ext: u8`).
2650     Static(P<Ty>, Mutability),
2651     /// A foreign type.
2652     Ty,
2653     /// A macro invocation.
2654     Macro(Mac),
2655 }
2656
2657 impl ForeignItemKind {
2658     pub fn descriptive_variant(&self) -> &str {
2659         match *self {
2660             ForeignItemKind::Fn(..) => "foreign function",
2661             ForeignItemKind::Static(..) => "foreign static item",
2662             ForeignItemKind::Ty => "foreign type",
2663             ForeignItemKind::Macro(..) => "macro in foreign module",
2664         }
2665     }
2666 }