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