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