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