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