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