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