]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
8018e005b12d72ee6c1e4da30dc2c4d49a8ef6a4
[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     Eq(
1400         /// Span of the `=` token.
1401         Span,
1402         /// Token stream of the "value".
1403         TokenStream,
1404     ),
1405 }
1406
1407 impl MacArgs {
1408     pub fn delim(&self) -> DelimToken {
1409         match self {
1410             MacArgs::Delimited(_, delim, _) => delim.to_token(),
1411             MacArgs::Empty | MacArgs::Eq(..) => token::NoDelim,
1412         }
1413     }
1414
1415     pub fn span(&self) -> Option<Span> {
1416         match *self {
1417             MacArgs::Empty => None,
1418             MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1419             MacArgs::Eq(eq_span, ref tokens) => Some(eq_span.to(tokens.span().unwrap_or(eq_span))),
1420         }
1421     }
1422
1423     /// Tokens inside the delimiters or after `=`.
1424     /// Proc macros see these tokens, for example.
1425     pub fn inner_tokens(&self) -> TokenStream {
1426         match self {
1427             MacArgs::Empty => TokenStream::default(),
1428             MacArgs::Delimited(.., tokens) |
1429             MacArgs::Eq(.., tokens) => tokens.clone(),
1430         }
1431     }
1432
1433     /// Tokens together with the delimiters or `=`.
1434     /// Use of this method generally means that something suboptimal or hacky is happening.
1435     pub fn outer_tokens(&self) -> TokenStream {
1436         match *self {
1437             MacArgs::Empty => TokenStream::default(),
1438             MacArgs::Delimited(dspan, delim, ref tokens) =>
1439                 TokenTree::Delimited(dspan, delim.to_token(), tokens.clone()).into(),
1440             MacArgs::Eq(eq_span, ref tokens) => iter::once(TokenTree::token(token::Eq, eq_span))
1441                                                 .chain(tokens.trees()).collect(),
1442         }
1443     }
1444
1445     /// Whether a macro with these arguments needs a semicolon
1446     /// when used as a standalone item or statement.
1447     pub fn need_semicolon(&self) -> bool {
1448         !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace ,_))
1449     }
1450 }
1451
1452 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1453 pub enum MacDelimiter {
1454     Parenthesis,
1455     Bracket,
1456     Brace,
1457 }
1458
1459 impl MacDelimiter {
1460     crate fn to_token(self) -> DelimToken {
1461         match self {
1462             MacDelimiter::Parenthesis => DelimToken::Paren,
1463             MacDelimiter::Bracket => DelimToken::Bracket,
1464             MacDelimiter::Brace => DelimToken::Brace,
1465         }
1466     }
1467
1468     pub fn from_token(delim: DelimToken) -> Option<MacDelimiter> {
1469         match delim {
1470             token::Paren => Some(MacDelimiter::Parenthesis),
1471             token::Bracket => Some(MacDelimiter::Bracket),
1472             token::Brace => Some(MacDelimiter::Brace),
1473             token::NoDelim => None,
1474         }
1475     }
1476 }
1477
1478 /// Represents a macro definition.
1479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1480 pub struct MacroDef {
1481     pub body: P<MacArgs>,
1482     /// `true` if macro was defined with `macro_rules`.
1483     pub legacy: bool,
1484 }
1485
1486 // Clippy uses Hash and PartialEq
1487 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1488 pub enum StrStyle {
1489     /// A regular string, like `"foo"`.
1490     Cooked,
1491     /// A raw string, like `r##"foo"##`.
1492     ///
1493     /// The value is the number of `#` symbols used.
1494     Raw(u16),
1495 }
1496
1497 /// An AST literal.
1498 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1499 pub struct Lit {
1500     /// The original literal token as written in source code.
1501     pub token: token::Lit,
1502     /// The "semantic" representation of the literal lowered from the original tokens.
1503     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1504     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1505     pub kind: LitKind,
1506     pub span: Span,
1507 }
1508
1509 /// Same as `Lit`, but restricted to string literals.
1510 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1511 pub struct StrLit {
1512     /// The original literal token as written in source code.
1513     pub style: StrStyle,
1514     pub symbol: Symbol,
1515     pub suffix: Option<Symbol>,
1516     pub span: Span,
1517     /// The unescaped "semantic" representation of the literal lowered from the original token.
1518     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1519     pub symbol_unescaped: Symbol,
1520 }
1521
1522 impl StrLit {
1523     crate fn as_lit(&self) -> Lit {
1524         let token_kind = match self.style {
1525             StrStyle::Cooked => token::Str,
1526             StrStyle::Raw(n) => token::StrRaw(n),
1527         };
1528         Lit {
1529             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1530             span: self.span,
1531             kind: LitKind::Str(self.symbol_unescaped, self.style),
1532         }
1533     }
1534 }
1535
1536 // Clippy uses Hash and PartialEq
1537 /// Type of the integer literal based on provided suffix.
1538 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1539 pub enum LitIntType {
1540     /// e.g. `42_i32`.
1541     Signed(IntTy),
1542     /// e.g. `42_u32`.
1543     Unsigned(UintTy),
1544     /// e.g. `42`.
1545     Unsuffixed,
1546 }
1547
1548 /// Type of the float literal based on provided suffix.
1549 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1550 pub enum LitFloatType {
1551     /// A float literal with a suffix (`1f32` or `1E10f32`).
1552     Suffixed(FloatTy),
1553     /// A float literal without a suffix (`1.0 or 1.0E10`).
1554     Unsuffixed,
1555 }
1556
1557 /// Literal kind.
1558 ///
1559 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1560 // Clippy uses Hash and PartialEq
1561 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1562 pub enum LitKind {
1563     /// A string literal (`"foo"`).
1564     Str(Symbol, StrStyle),
1565     /// A byte string (`b"foo"`).
1566     ByteStr(Lrc<Vec<u8>>),
1567     /// A byte char (`b'f'`).
1568     Byte(u8),
1569     /// A character literal (`'a'`).
1570     Char(char),
1571     /// An integer literal (`1`).
1572     Int(u128, LitIntType),
1573     /// A float literal (`1f64` or `1E10f64`).
1574     Float(Symbol, LitFloatType),
1575     /// A boolean literal.
1576     Bool(bool),
1577     /// Placeholder for a literal that wasn't well-formed in some way.
1578     Err(Symbol),
1579 }
1580
1581 impl LitKind {
1582     /// Returns `true` if this literal is a string.
1583     pub fn is_str(&self) -> bool {
1584         match *self {
1585             LitKind::Str(..) => true,
1586             _ => false,
1587         }
1588     }
1589
1590     /// Returns `true` if this literal is byte literal string.
1591     pub fn is_bytestr(&self) -> bool {
1592         match self {
1593             LitKind::ByteStr(_) => true,
1594             _ => false,
1595         }
1596     }
1597
1598     /// Returns `true` if this is a numeric literal.
1599     pub fn is_numeric(&self) -> bool {
1600         match *self {
1601             LitKind::Int(..) | LitKind::Float(..) => true,
1602             _ => false,
1603         }
1604     }
1605
1606     /// Returns `true` if this literal has no suffix.
1607     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1608     pub fn is_unsuffixed(&self) -> bool {
1609         !self.is_suffixed()
1610     }
1611
1612     /// Returns `true` if this literal has a suffix.
1613     pub fn is_suffixed(&self) -> bool {
1614         match *self {
1615             // suffixed variants
1616             LitKind::Int(_, LitIntType::Signed(..))
1617             | LitKind::Int(_, LitIntType::Unsigned(..))
1618             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1619             // unsuffixed variants
1620             LitKind::Str(..)
1621             | LitKind::ByteStr(..)
1622             | LitKind::Byte(..)
1623             | LitKind::Char(..)
1624             | LitKind::Int(_, LitIntType::Unsuffixed)
1625             | LitKind::Float(_, LitFloatType::Unsuffixed)
1626             | LitKind::Bool(..)
1627             | LitKind::Err(..) => false,
1628         }
1629     }
1630 }
1631
1632 // N.B., If you change this, you'll probably want to change the corresponding
1633 // type structure in `middle/ty.rs` as well.
1634 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1635 pub struct MutTy {
1636     pub ty: P<Ty>,
1637     pub mutbl: Mutability,
1638 }
1639
1640 /// Represents a function's signature in a trait declaration,
1641 /// trait implementation, or free function.
1642 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1643 pub struct FnSig {
1644     pub header: FnHeader,
1645     pub decl: P<FnDecl>,
1646 }
1647
1648 /// Represents an item declaration within a trait declaration,
1649 /// possibly including a default implementation. A trait item is
1650 /// either required (meaning it doesn't have an implementation, just a
1651 /// signature) or provided (meaning it has a default implementation).
1652 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1653 pub struct TraitItem {
1654     pub attrs: Vec<Attribute>,
1655     pub id: NodeId,
1656     pub span: Span,
1657     pub vis: Visibility,
1658     pub ident: Ident,
1659
1660     pub generics: Generics,
1661     pub kind: TraitItemKind,
1662     /// See `Item::tokens` for what this is.
1663     pub tokens: Option<TokenStream>,
1664 }
1665
1666 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1667 pub enum TraitItemKind {
1668     Const(P<Ty>, Option<P<Expr>>),
1669     Method(FnSig, Option<P<Block>>),
1670     Type(GenericBounds, Option<P<Ty>>),
1671     Macro(Mac),
1672 }
1673
1674 /// Represents anything within an `impl` block.
1675 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1676 pub struct ImplItem {
1677     pub attrs: Vec<Attribute>,
1678     pub id: NodeId,
1679     pub span: Span,
1680     pub vis: Visibility,
1681     pub ident: Ident,
1682
1683     pub defaultness: Defaultness,
1684     pub generics: Generics,
1685     pub kind: ImplItemKind,
1686     /// See `Item::tokens` for what this is.
1687     pub tokens: Option<TokenStream>,
1688 }
1689
1690 /// Represents various kinds of content within an `impl`.
1691 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1692 pub enum ImplItemKind {
1693     Const(P<Ty>, P<Expr>),
1694     Method(FnSig, P<Block>),
1695     TyAlias(P<Ty>),
1696     Macro(Mac),
1697 }
1698
1699 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1700          RustcEncodable, RustcDecodable, Debug)]
1701 pub enum FloatTy {
1702     F32,
1703     F64,
1704 }
1705
1706 impl FloatTy {
1707     pub fn name_str(self) -> &'static str {
1708         match self {
1709             FloatTy::F32 => "f32",
1710             FloatTy::F64 => "f64",
1711         }
1712     }
1713
1714     pub fn name(self) -> Symbol {
1715         match self {
1716             FloatTy::F32 => sym::f32,
1717             FloatTy::F64 => sym::f64,
1718         }
1719     }
1720
1721     pub fn bit_width(self) -> usize {
1722         match self {
1723             FloatTy::F32 => 32,
1724             FloatTy::F64 => 64,
1725         }
1726     }
1727 }
1728
1729 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1730          RustcEncodable, RustcDecodable, Debug)]
1731 pub enum IntTy {
1732     Isize,
1733     I8,
1734     I16,
1735     I32,
1736     I64,
1737     I128,
1738 }
1739
1740 impl IntTy {
1741     pub fn name_str(&self) -> &'static str {
1742         match *self {
1743             IntTy::Isize => "isize",
1744             IntTy::I8 => "i8",
1745             IntTy::I16 => "i16",
1746             IntTy::I32 => "i32",
1747             IntTy::I64 => "i64",
1748             IntTy::I128 => "i128",
1749         }
1750     }
1751
1752     pub fn name(&self) -> Symbol {
1753         match *self {
1754             IntTy::Isize => sym::isize,
1755             IntTy::I8 => sym::i8,
1756             IntTy::I16 => sym::i16,
1757             IntTy::I32 => sym::i32,
1758             IntTy::I64 => sym::i64,
1759             IntTy::I128 => sym::i128,
1760         }
1761     }
1762
1763     pub fn val_to_string(&self, val: i128) -> String {
1764         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1765         // are parsed as `u128`, so we wouldn't want to print an extra negative
1766         // sign.
1767         format!("{}{}", val as u128, self.name_str())
1768     }
1769
1770     pub fn bit_width(&self) -> Option<usize> {
1771         Some(match *self {
1772             IntTy::Isize => return None,
1773             IntTy::I8 => 8,
1774             IntTy::I16 => 16,
1775             IntTy::I32 => 32,
1776             IntTy::I64 => 64,
1777             IntTy::I128 => 128,
1778         })
1779     }
1780
1781     pub fn normalize(&self, target_width: u32) -> Self {
1782         match self {
1783             IntTy::Isize => match target_width {
1784                 16 => IntTy::I16,
1785                 32 => IntTy::I32,
1786                 64 => IntTy::I64,
1787                 _ => unreachable!(),
1788             },
1789             _ => *self,
1790         }
1791     }
1792 }
1793
1794 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1795          RustcEncodable, RustcDecodable, Copy, Debug)]
1796 pub enum UintTy {
1797     Usize,
1798     U8,
1799     U16,
1800     U32,
1801     U64,
1802     U128,
1803 }
1804
1805 impl UintTy {
1806     pub fn name_str(&self) -> &'static str {
1807         match *self {
1808             UintTy::Usize => "usize",
1809             UintTy::U8 => "u8",
1810             UintTy::U16 => "u16",
1811             UintTy::U32 => "u32",
1812             UintTy::U64 => "u64",
1813             UintTy::U128 => "u128",
1814         }
1815     }
1816
1817     pub fn name(&self) -> Symbol {
1818         match *self {
1819             UintTy::Usize => sym::usize,
1820             UintTy::U8 => sym::u8,
1821             UintTy::U16 => sym::u16,
1822             UintTy::U32 => sym::u32,
1823             UintTy::U64 => sym::u64,
1824             UintTy::U128 => sym::u128,
1825         }
1826     }
1827
1828     pub fn val_to_string(&self, val: u128) -> String {
1829         format!("{}{}", val, self.name_str())
1830     }
1831
1832     pub fn bit_width(&self) -> Option<usize> {
1833         Some(match *self {
1834             UintTy::Usize => return None,
1835             UintTy::U8 => 8,
1836             UintTy::U16 => 16,
1837             UintTy::U32 => 32,
1838             UintTy::U64 => 64,
1839             UintTy::U128 => 128,
1840         })
1841     }
1842
1843     pub fn normalize(&self, target_width: u32) -> Self {
1844         match self {
1845             UintTy::Usize => match target_width {
1846                 16 => UintTy::U16,
1847                 32 => UintTy::U32,
1848                 64 => UintTy::U64,
1849                 _ => unreachable!(),
1850             },
1851             _ => *self,
1852         }
1853     }
1854 }
1855
1856 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1857 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1858 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1859 pub struct AssocTyConstraint {
1860     pub id: NodeId,
1861     pub ident: Ident,
1862     pub kind: AssocTyConstraintKind,
1863     pub span: Span,
1864 }
1865
1866 /// The kinds of an `AssocTyConstraint`.
1867 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1868 pub enum AssocTyConstraintKind {
1869     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1870     Equality {
1871         ty: P<Ty>,
1872     },
1873     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1874     Bound {
1875         bounds: GenericBounds,
1876     },
1877 }
1878
1879 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1880 pub struct Ty {
1881     pub id: NodeId,
1882     pub kind: TyKind,
1883     pub span: Span,
1884 }
1885
1886 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1887 pub struct BareFnTy {
1888     pub unsafety: Unsafety,
1889     pub ext: Extern,
1890     pub generic_params: Vec<GenericParam>,
1891     pub decl: P<FnDecl>,
1892 }
1893
1894 /// The various kinds of type recognized by the compiler.
1895 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1896 pub enum TyKind {
1897     /// A variable-length slice (`[T]`).
1898     Slice(P<Ty>),
1899     /// A fixed length array (`[T; n]`).
1900     Array(P<Ty>, AnonConst),
1901     /// A raw pointer (`*const T` or `*mut T`).
1902     Ptr(MutTy),
1903     /// A reference (`&'a T` or `&'a mut T`).
1904     Rptr(Option<Lifetime>, MutTy),
1905     /// A bare function (e.g., `fn(usize) -> bool`).
1906     BareFn(P<BareFnTy>),
1907     /// The never type (`!`).
1908     Never,
1909     /// A tuple (`(A, B, C, D,...)`).
1910     Tup(Vec<P<Ty>>),
1911     /// A path (`module::module::...::Type`), optionally
1912     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1913     ///
1914     /// Type parameters are stored in the `Path` itself.
1915     Path(Option<QSelf>, Path),
1916     /// A trait object type `Bound1 + Bound2 + Bound3`
1917     /// where `Bound` is a trait or a lifetime.
1918     TraitObject(GenericBounds, TraitObjectSyntax),
1919     /// An `impl Bound1 + Bound2 + Bound3` type
1920     /// where `Bound` is a trait or a lifetime.
1921     ///
1922     /// The `NodeId` exists to prevent lowering from having to
1923     /// generate `NodeId`s on the fly, which would complicate
1924     /// the generation of opaque `type Foo = impl Trait` items significantly.
1925     ImplTrait(NodeId, GenericBounds),
1926     /// No-op; kept solely so that we can pretty-print faithfully.
1927     Paren(P<Ty>),
1928     /// Unused for now.
1929     Typeof(AnonConst),
1930     /// This means the type should be inferred instead of it having been
1931     /// specified. This can appear anywhere in a type.
1932     Infer,
1933     /// Inferred type of a `self` or `&self` argument in a method.
1934     ImplicitSelf,
1935     /// A macro in the type position.
1936     Mac(Mac),
1937     /// Placeholder for a kind that has failed to be defined.
1938     Err,
1939     /// Placeholder for a `va_list`.
1940     CVarArgs,
1941 }
1942
1943 impl TyKind {
1944     pub fn is_implicit_self(&self) -> bool {
1945         if let TyKind::ImplicitSelf = *self {
1946             true
1947         } else {
1948             false
1949         }
1950     }
1951
1952     pub fn is_unit(&self) -> bool {
1953         if let TyKind::Tup(ref tys) = *self {
1954             tys.is_empty()
1955         } else {
1956             false
1957         }
1958     }
1959
1960     /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1961     /// in lowering to avoid making larger changes there and beyond.
1962     pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1963         match self {
1964             Self::ImplTrait(_, bounds) => Some(bounds),
1965             _ => None,
1966         }
1967     }
1968 }
1969
1970 /// Syntax used to declare a trait object.
1971 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1972 pub enum TraitObjectSyntax {
1973     Dyn,
1974     None,
1975 }
1976
1977 /// Inline assembly dialect.
1978 ///
1979 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1980 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1981 pub enum AsmDialect {
1982     Att,
1983     Intel,
1984 }
1985
1986 /// Inline assembly.
1987 ///
1988 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1989 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1990 pub struct InlineAsmOutput {
1991     pub constraint: Symbol,
1992     pub expr: P<Expr>,
1993     pub is_rw: bool,
1994     pub is_indirect: bool,
1995 }
1996
1997 /// Inline assembly.
1998 ///
1999 /// E.g., `asm!("NOP");`.
2000 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2001 pub struct InlineAsm {
2002     pub asm: Symbol,
2003     pub asm_str_style: StrStyle,
2004     pub outputs: Vec<InlineAsmOutput>,
2005     pub inputs: Vec<(Symbol, P<Expr>)>,
2006     pub clobbers: Vec<Symbol>,
2007     pub volatile: bool,
2008     pub alignstack: bool,
2009     pub dialect: AsmDialect,
2010 }
2011
2012 /// A parameter in a function header.
2013 ///
2014 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2016 pub struct Param {
2017     pub attrs: ThinVec<Attribute>,
2018     pub ty: P<Ty>,
2019     pub pat: P<Pat>,
2020     pub id: NodeId,
2021     pub span: Span,
2022     pub is_placeholder: bool,
2023 }
2024
2025 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2026 ///
2027 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2029 pub enum SelfKind {
2030     /// `self`, `mut self`
2031     Value(Mutability),
2032     /// `&'lt self`, `&'lt mut self`
2033     Region(Option<Lifetime>, Mutability),
2034     /// `self: TYPE`, `mut self: TYPE`
2035     Explicit(P<Ty>, Mutability),
2036 }
2037
2038 pub type ExplicitSelf = Spanned<SelfKind>;
2039
2040 impl Param {
2041     /// Attempts to cast parameter to `ExplicitSelf`.
2042     pub fn to_self(&self) -> Option<ExplicitSelf> {
2043         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2044             if ident.name == kw::SelfLower {
2045                 return match self.ty.kind {
2046                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2047                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2048                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2049                     }
2050                     _ => Some(respan(
2051                         self.pat.span.to(self.ty.span),
2052                         SelfKind::Explicit(self.ty.clone(), mutbl),
2053                     )),
2054                 };
2055             }
2056         }
2057         None
2058     }
2059
2060     /// Returns `true` if parameter is `self`.
2061     pub fn is_self(&self) -> bool {
2062         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2063             ident.name == kw::SelfLower
2064         } else {
2065             false
2066         }
2067     }
2068
2069     /// Builds a `Param` object from `ExplicitSelf`.
2070     pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2071         let span = eself.span.to(eself_ident.span);
2072         let infer_ty = P(Ty {
2073             id: DUMMY_NODE_ID,
2074             kind: TyKind::ImplicitSelf,
2075             span,
2076         });
2077         let param = |mutbl, ty| Param {
2078             attrs,
2079             pat: P(Pat {
2080                 id: DUMMY_NODE_ID,
2081                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2082                 span,
2083             }),
2084             span,
2085             ty,
2086             id: DUMMY_NODE_ID,
2087             is_placeholder: false
2088         };
2089         match eself.node {
2090             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2091             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2092             SelfKind::Region(lt, mutbl) => param(
2093                 Mutability::Immutable,
2094                 P(Ty {
2095                     id: DUMMY_NODE_ID,
2096                     kind: TyKind::Rptr(
2097                         lt,
2098                         MutTy {
2099                             ty: infer_ty,
2100                             mutbl,
2101                         },
2102                     ),
2103                     span,
2104                 }),
2105             ),
2106         }
2107     }
2108 }
2109
2110 /// A signature (not the body) of a function declaration.
2111 ///
2112 /// E.g., `fn foo(bar: baz)`.
2113 ///
2114 /// Please note that it's different from `FnHeader` structure
2115 /// which contains metadata about function safety, asyncness, constness and ABI.
2116 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2117 pub struct FnDecl {
2118     pub inputs: Vec<Param>,
2119     pub output: FunctionRetTy,
2120 }
2121
2122 impl FnDecl {
2123     pub fn get_self(&self) -> Option<ExplicitSelf> {
2124         self.inputs.get(0).and_then(Param::to_self)
2125     }
2126     pub fn has_self(&self) -> bool {
2127         self.inputs.get(0).map_or(false, Param::is_self)
2128     }
2129     pub fn c_variadic(&self) -> bool {
2130         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2131             TyKind::CVarArgs => true,
2132             _ => false,
2133         })
2134     }
2135 }
2136
2137 /// Is the trait definition an auto trait?
2138 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2139 pub enum IsAuto {
2140     Yes,
2141     No,
2142 }
2143
2144 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2145          RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2146 pub enum Unsafety {
2147     Unsafe,
2148     Normal,
2149 }
2150
2151 impl Unsafety {
2152     pub fn prefix_str(&self) -> &'static str {
2153         match self {
2154             Unsafety::Unsafe => "unsafe ",
2155             Unsafety::Normal => "",
2156         }
2157     }
2158 }
2159
2160 impl fmt::Display for Unsafety {
2161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2162         fmt::Display::fmt(
2163             match *self {
2164                 Unsafety::Normal => "normal",
2165                 Unsafety::Unsafe => "unsafe",
2166             },
2167             f,
2168         )
2169     }
2170 }
2171
2172 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2173 pub enum IsAsync {
2174     Async {
2175         closure_id: NodeId,
2176         return_impl_trait_id: NodeId,
2177     },
2178     NotAsync,
2179 }
2180
2181 impl IsAsync {
2182     pub fn is_async(self) -> bool {
2183         if let IsAsync::Async { .. } = self {
2184             true
2185         } else {
2186             false
2187         }
2188     }
2189
2190     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2191     pub fn opt_return_id(self) -> Option<NodeId> {
2192         match self {
2193             IsAsync::Async {
2194                 return_impl_trait_id,
2195                 ..
2196             } => Some(return_impl_trait_id),
2197             IsAsync::NotAsync => None,
2198         }
2199     }
2200 }
2201
2202 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2203 pub enum Constness {
2204     Const,
2205     NotConst,
2206 }
2207
2208 /// Item defaultness.
2209 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2210 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2211 pub enum Defaultness {
2212     Default,
2213     Final,
2214 }
2215
2216 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2217 pub enum ImplPolarity {
2218     /// `impl Trait for Type`
2219     Positive,
2220     /// `impl !Trait for Type`
2221     Negative,
2222 }
2223
2224 impl fmt::Debug for ImplPolarity {
2225     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226         match *self {
2227             ImplPolarity::Positive => "positive".fmt(f),
2228             ImplPolarity::Negative => "negative".fmt(f),
2229         }
2230     }
2231 }
2232
2233 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2234 pub enum FunctionRetTy {
2235     /// Returns type is not specified.
2236     ///
2237     /// Functions default to `()` and closures default to inference.
2238     /// Span points to where return type would be inserted.
2239     Default(Span),
2240     /// Everything else.
2241     Ty(P<Ty>),
2242 }
2243
2244 impl FunctionRetTy {
2245     pub fn span(&self) -> Span {
2246         match *self {
2247             FunctionRetTy::Default(span) => span,
2248             FunctionRetTy::Ty(ref ty) => ty.span,
2249         }
2250     }
2251 }
2252
2253 /// Module declaration.
2254 ///
2255 /// E.g., `mod foo;` or `mod foo { .. }`.
2256 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2257 pub struct Mod {
2258     /// A span from the first token past `{` to the last token until `}`.
2259     /// For `mod foo;`, the inner span ranges from the first token
2260     /// to the last token in the external file.
2261     pub inner: Span,
2262     pub items: Vec<P<Item>>,
2263     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2264     pub inline: bool,
2265 }
2266
2267 /// Foreign module declaration.
2268 ///
2269 /// E.g., `extern { .. }` or `extern C { .. }`.
2270 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2271 pub struct ForeignMod {
2272     pub abi: Option<StrLit>,
2273     pub items: Vec<ForeignItem>,
2274 }
2275
2276 /// Global inline assembly.
2277 ///
2278 /// Also known as "module-level assembly" or "file-scoped assembly".
2279 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2280 pub struct GlobalAsm {
2281     pub asm: Symbol,
2282 }
2283
2284 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2285 pub struct EnumDef {
2286     pub variants: Vec<Variant>,
2287 }
2288 /// Enum variant.
2289 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2290 pub struct Variant {
2291     /// Attributes of the variant.
2292     pub attrs: Vec<Attribute>,
2293     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2294     pub id: NodeId,
2295     /// Span
2296     pub span: Span,
2297     /// The visibility of the variant. Syntactically accepted but not semantically.
2298     pub vis: Visibility,
2299     /// Name of the variant.
2300     pub ident: Ident,
2301
2302     /// Fields and constructor id of the variant.
2303     pub data: VariantData,
2304     /// Explicit discriminant, e.g., `Foo = 1`.
2305     pub disr_expr: Option<AnonConst>,
2306     /// Is a macro placeholder
2307     pub is_placeholder: bool,
2308 }
2309
2310 /// Part of `use` item to the right of its prefix.
2311 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2312 pub enum UseTreeKind {
2313     /// `use prefix` or `use prefix as rename`
2314     ///
2315     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2316     /// namespace.
2317     Simple(Option<Ident>, NodeId, NodeId),
2318     /// `use prefix::{...}`
2319     Nested(Vec<(UseTree, NodeId)>),
2320     /// `use prefix::*`
2321     Glob,
2322 }
2323
2324 /// A tree of paths sharing common prefixes.
2325 /// Used in `use` items both at top-level and inside of braces in import groups.
2326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2327 pub struct UseTree {
2328     pub prefix: Path,
2329     pub kind: UseTreeKind,
2330     pub span: Span,
2331 }
2332
2333 impl UseTree {
2334     pub fn ident(&self) -> Ident {
2335         match self.kind {
2336             UseTreeKind::Simple(Some(rename), ..) => rename,
2337             UseTreeKind::Simple(None, ..) => {
2338                 self.prefix
2339                     .segments
2340                     .last()
2341                     .expect("empty prefix in a simple import")
2342                     .ident
2343             }
2344             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2345         }
2346     }
2347 }
2348
2349 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2350 /// are contained as statements within items. These two cases need to be
2351 /// distinguished for pretty-printing.
2352 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2353 pub enum AttrStyle {
2354     Outer,
2355     Inner,
2356 }
2357
2358 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2359 pub struct AttrId(pub usize);
2360
2361 impl Idx for AttrId {
2362     fn new(idx: usize) -> Self {
2363         AttrId(idx)
2364     }
2365     fn index(self) -> usize {
2366         self.0
2367     }
2368 }
2369
2370 impl rustc_serialize::Encodable for AttrId {
2371     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2372         s.emit_unit()
2373     }
2374 }
2375
2376 impl rustc_serialize::Decodable for AttrId {
2377     fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2378         d.read_nil().map(|_| crate::attr::mk_attr_id())
2379     }
2380 }
2381
2382 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2383 pub struct AttrItem {
2384     pub path: Path,
2385     pub args: MacArgs,
2386 }
2387
2388 /// Metadata associated with an item.
2389 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2390 pub struct Attribute {
2391     pub kind: AttrKind,
2392     pub id: AttrId,
2393     /// Denotes if the attribute decorates the following construct (outer)
2394     /// or the construct this attribute is contained within (inner).
2395     pub style: AttrStyle,
2396     pub span: Span,
2397 }
2398
2399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2400 pub enum AttrKind {
2401     /// A normal attribute.
2402     Normal(AttrItem),
2403
2404     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2405     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2406     /// variant (which is much less compact and thus more expensive).
2407     ///
2408     /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2409     /// for this variant, but this may change in the future.
2410     /// ```
2411     DocComment(Symbol),
2412 }
2413
2414 /// `TraitRef`s appear in impls.
2415 ///
2416 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2417 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2418 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2419 /// same as the impl's `NodeId`).
2420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2421 pub struct TraitRef {
2422     pub path: Path,
2423     pub ref_id: NodeId,
2424 }
2425
2426 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2427 pub struct PolyTraitRef {
2428     /// The `'a` in `<'a> Foo<&'a T>`.
2429     pub bound_generic_params: Vec<GenericParam>,
2430
2431     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2432     pub trait_ref: TraitRef,
2433
2434     pub span: Span,
2435 }
2436
2437 impl PolyTraitRef {
2438     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2439         PolyTraitRef {
2440             bound_generic_params: generic_params,
2441             trait_ref: TraitRef {
2442                 path,
2443                 ref_id: DUMMY_NODE_ID,
2444             },
2445             span,
2446         }
2447     }
2448 }
2449
2450 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2451 pub enum CrateSugar {
2452     /// Source is `pub(crate)`.
2453     PubCrate,
2454
2455     /// Source is (just) `crate`.
2456     JustCrate,
2457 }
2458
2459 pub type Visibility = Spanned<VisibilityKind>;
2460
2461 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2462 pub enum VisibilityKind {
2463     Public,
2464     Crate(CrateSugar),
2465     Restricted { path: P<Path>, id: NodeId },
2466     Inherited,
2467 }
2468
2469 impl VisibilityKind {
2470     pub fn is_pub(&self) -> bool {
2471         if let VisibilityKind::Public = *self {
2472             true
2473         } else {
2474             false
2475         }
2476     }
2477 }
2478
2479 /// Field of a struct.
2480 ///
2481 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2482 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2483 pub struct StructField {
2484     pub attrs: Vec<Attribute>,
2485     pub id: NodeId,
2486     pub span: Span,
2487     pub vis: Visibility,
2488     pub ident: Option<Ident>,
2489
2490     pub ty: P<Ty>,
2491     pub is_placeholder: bool,
2492 }
2493
2494 /// Fields and constructor ids of enum variants and structs.
2495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2496 pub enum VariantData {
2497     /// Struct variant.
2498     ///
2499     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2500     Struct(Vec<StructField>, bool),
2501     /// Tuple variant.
2502     ///
2503     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2504     Tuple(Vec<StructField>, NodeId),
2505     /// Unit variant.
2506     ///
2507     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2508     Unit(NodeId),
2509 }
2510
2511 impl VariantData {
2512     /// Return the fields of this variant.
2513     pub fn fields(&self) -> &[StructField] {
2514         match *self {
2515             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2516             _ => &[],
2517         }
2518     }
2519
2520     /// Return the `NodeId` of this variant's constructor, if it has one.
2521     pub fn ctor_id(&self) -> Option<NodeId> {
2522         match *self {
2523             VariantData::Struct(..) => None,
2524             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2525         }
2526     }
2527 }
2528
2529 /// An item.
2530 ///
2531 /// The name might be a dummy name in case of anonymous items.
2532 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2533 pub struct Item {
2534     pub attrs: Vec<Attribute>,
2535     pub id: NodeId,
2536     pub span: Span,
2537     pub vis: Visibility,
2538     pub ident: Ident,
2539
2540     pub kind: ItemKind,
2541
2542     /// Original tokens this item was parsed from. This isn't necessarily
2543     /// available for all items, although over time more and more items should
2544     /// have this be `Some`. Right now this is primarily used for procedural
2545     /// macros, notably custom attributes.
2546     ///
2547     /// Note that the tokens here do not include the outer attributes, but will
2548     /// include inner attributes.
2549     pub tokens: Option<TokenStream>,
2550 }
2551
2552 impl Item {
2553     /// Return the span that encompasses the attributes.
2554     pub fn span_with_attributes(&self) -> Span {
2555         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2556     }
2557 }
2558
2559 /// `extern` qualifier on a function item or function type.
2560 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2561 pub enum Extern {
2562     None,
2563     Implicit,
2564     Explicit(StrLit),
2565 }
2566
2567 impl Extern {
2568     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2569         abi.map_or(Extern::Implicit, Extern::Explicit)
2570     }
2571 }
2572
2573 /// A function header.
2574 ///
2575 /// All the information between the visibility and the name of the function is
2576 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2577 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2578 pub struct FnHeader {
2579     pub unsafety: Unsafety,
2580     pub asyncness: Spanned<IsAsync>,
2581     pub constness: Spanned<Constness>,
2582     pub ext: Extern,
2583 }
2584
2585 impl Default for FnHeader {
2586     fn default() -> FnHeader {
2587         FnHeader {
2588             unsafety: Unsafety::Normal,
2589             asyncness: dummy_spanned(IsAsync::NotAsync),
2590             constness: dummy_spanned(Constness::NotConst),
2591             ext: Extern::None,
2592         }
2593     }
2594 }
2595
2596 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2597 pub enum ItemKind {
2598     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2599     ///
2600     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2601     ExternCrate(Option<Name>),
2602     /// A use declaration item (`use`).
2603     ///
2604     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2605     Use(P<UseTree>),
2606     /// A static item (`static`).
2607     ///
2608     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2609     Static(P<Ty>, Mutability, P<Expr>),
2610     /// A constant item (`const`).
2611     ///
2612     /// E.g., `const FOO: i32 = 42;`.
2613     Const(P<Ty>, P<Expr>),
2614     /// A function declaration (`fn`).
2615     ///
2616     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2617     Fn(FnSig, Generics, P<Block>),
2618     /// A module declaration (`mod`).
2619     ///
2620     /// E.g., `mod foo;` or `mod foo { .. }`.
2621     Mod(Mod),
2622     /// An external module (`extern`).
2623     ///
2624     /// E.g., `extern {}` or `extern "C" {}`.
2625     ForeignMod(ForeignMod),
2626     /// Module-level inline assembly (from `global_asm!()`).
2627     GlobalAsm(P<GlobalAsm>),
2628     /// A type alias (`type`).
2629     ///
2630     /// E.g., `type Foo = Bar<u8>;`.
2631     TyAlias(P<Ty>, Generics),
2632     /// An enum definition (`enum`).
2633     ///
2634     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2635     Enum(EnumDef, Generics),
2636     /// A struct definition (`struct`).
2637     ///
2638     /// E.g., `struct Foo<A> { x: A }`.
2639     Struct(VariantData, Generics),
2640     /// A union definition (`union`).
2641     ///
2642     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2643     Union(VariantData, Generics),
2644     /// A trait declaration (`trait`).
2645     ///
2646     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2647     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2648     /// Trait alias
2649     ///
2650     /// E.g., `trait Foo = Bar + Quux;`.
2651     TraitAlias(Generics, GenericBounds),
2652     /// An implementation.
2653     ///
2654     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2655     Impl(
2656         Unsafety,
2657         ImplPolarity,
2658         Defaultness,
2659         Generics,
2660         Option<TraitRef>, // (optional) trait this impl implements
2661         P<Ty>,            // self
2662         Vec<ImplItem>,
2663     ),
2664     /// A macro invocation.
2665     ///
2666     /// E.g., `foo!(..)`.
2667     Mac(Mac),
2668
2669     /// A macro definition.
2670     MacroDef(MacroDef),
2671 }
2672
2673 impl ItemKind {
2674     pub fn descriptive_variant(&self) -> &str {
2675         match *self {
2676             ItemKind::ExternCrate(..) => "extern crate",
2677             ItemKind::Use(..) => "use",
2678             ItemKind::Static(..) => "static item",
2679             ItemKind::Const(..) => "constant item",
2680             ItemKind::Fn(..) => "function",
2681             ItemKind::Mod(..) => "module",
2682             ItemKind::ForeignMod(..) => "foreign module",
2683             ItemKind::GlobalAsm(..) => "global asm",
2684             ItemKind::TyAlias(..) => "type alias",
2685             ItemKind::Enum(..) => "enum",
2686             ItemKind::Struct(..) => "struct",
2687             ItemKind::Union(..) => "union",
2688             ItemKind::Trait(..) => "trait",
2689             ItemKind::TraitAlias(..) => "trait alias",
2690             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2691         }
2692     }
2693 }
2694
2695 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2696 pub struct ForeignItem {
2697     pub attrs: Vec<Attribute>,
2698     pub id: NodeId,
2699     pub span: Span,
2700     pub vis: Visibility,
2701     pub ident: Ident,
2702
2703     pub kind: ForeignItemKind,
2704 }
2705
2706 /// An item within an `extern` block.
2707 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2708 pub enum ForeignItemKind {
2709     /// A foreign function.
2710     Fn(P<FnDecl>, Generics),
2711     /// A foreign static item (`static ext: u8`).
2712     Static(P<Ty>, Mutability),
2713     /// A foreign type.
2714     Ty,
2715     /// A macro invocation.
2716     Macro(Mac),
2717 }
2718
2719 impl ForeignItemKind {
2720     pub fn descriptive_variant(&self) -> &str {
2721         match *self {
2722             ForeignItemKind::Fn(..) => "foreign function",
2723             ForeignItemKind::Static(..) => "foreign static item",
2724             ForeignItemKind::Ty => "foreign type",
2725             ForeignItemKind::Macro(..) => "macro in foreign module",
2726         }
2727     }
2728 }