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