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