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