]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Rollup merge of #66663 - RalfJung:miri-leaks, r=oli-obk
[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 /// The kind of borrow in an `AddrOf` expression,
768 /// e.g., `&place` or `&raw const place`.
769 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
770 #[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
771 pub enum BorrowKind {
772     /// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
773     /// The resulting type is either `*const T` or `*mut T`
774     /// where `T = typeof($expr)`.
775     Ref,
776     /// A normal borrow, `&$expr` or `&mut $expr`.
777     /// The resulting type is either `&'a T` or `&'a mut T`
778     /// where `T = typeof($expr)` and `'a` is some lifetime.
779     Raw,
780 }
781
782 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
783 pub enum BinOpKind {
784     /// The `+` operator (addition)
785     Add,
786     /// The `-` operator (subtraction)
787     Sub,
788     /// The `*` operator (multiplication)
789     Mul,
790     /// The `/` operator (division)
791     Div,
792     /// The `%` operator (modulus)
793     Rem,
794     /// The `&&` operator (logical and)
795     And,
796     /// The `||` operator (logical or)
797     Or,
798     /// The `^` operator (bitwise xor)
799     BitXor,
800     /// The `&` operator (bitwise and)
801     BitAnd,
802     /// The `|` operator (bitwise or)
803     BitOr,
804     /// The `<<` operator (shift left)
805     Shl,
806     /// The `>>` operator (shift right)
807     Shr,
808     /// The `==` operator (equality)
809     Eq,
810     /// The `<` operator (less than)
811     Lt,
812     /// The `<=` operator (less than or equal to)
813     Le,
814     /// The `!=` operator (not equal to)
815     Ne,
816     /// The `>=` operator (greater than or equal to)
817     Ge,
818     /// The `>` operator (greater than)
819     Gt,
820 }
821
822 impl BinOpKind {
823     pub fn to_string(&self) -> &'static str {
824         use BinOpKind::*;
825         match *self {
826             Add => "+",
827             Sub => "-",
828             Mul => "*",
829             Div => "/",
830             Rem => "%",
831             And => "&&",
832             Or => "||",
833             BitXor => "^",
834             BitAnd => "&",
835             BitOr => "|",
836             Shl => "<<",
837             Shr => ">>",
838             Eq => "==",
839             Lt => "<",
840             Le => "<=",
841             Ne => "!=",
842             Ge => ">=",
843             Gt => ">",
844         }
845     }
846     pub fn lazy(&self) -> bool {
847         match *self {
848             BinOpKind::And | BinOpKind::Or => true,
849             _ => false,
850         }
851     }
852
853     pub fn is_shift(&self) -> bool {
854         match *self {
855             BinOpKind::Shl | BinOpKind::Shr => true,
856             _ => false,
857         }
858     }
859
860     pub fn is_comparison(&self) -> bool {
861         use BinOpKind::*;
862         // Note for developers: please keep this as is;
863         // we want compilation to fail if another variant is added.
864         match *self {
865             Eq | Lt | Le | Ne | Gt | Ge => true,
866             And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
867         }
868     }
869
870     /// Returns `true` if the binary operator takes its arguments by value
871     pub fn is_by_value(&self) -> bool {
872         !self.is_comparison()
873     }
874 }
875
876 pub type BinOp = Spanned<BinOpKind>;
877
878 /// Unary operator.
879 ///
880 /// Note that `&data` is not an operator, it's an `AddrOf` expression.
881 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
882 pub enum UnOp {
883     /// The `*` operator for dereferencing
884     Deref,
885     /// The `!` operator for logical inversion
886     Not,
887     /// The `-` operator for negation
888     Neg,
889 }
890
891 impl UnOp {
892     /// Returns `true` if the unary operator takes its argument by value
893     pub fn is_by_value(u: UnOp) -> bool {
894         match u {
895             UnOp::Neg | UnOp::Not => true,
896             _ => false,
897         }
898     }
899
900     pub fn to_string(op: UnOp) -> &'static str {
901         match op {
902             UnOp::Deref => "*",
903             UnOp::Not => "!",
904             UnOp::Neg => "-",
905         }
906     }
907 }
908
909 /// A statement
910 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
911 pub struct Stmt {
912     pub id: NodeId,
913     pub kind: StmtKind,
914     pub span: Span,
915 }
916
917 impl Stmt {
918     pub fn add_trailing_semicolon(mut self) -> Self {
919         self.kind = match self.kind {
920             StmtKind::Expr(expr) => StmtKind::Semi(expr),
921             StmtKind::Mac(mac) => {
922                 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
923             }
924             kind => kind,
925         };
926         self
927     }
928
929     pub fn is_item(&self) -> bool {
930         match self.kind {
931             StmtKind::Item(_) => true,
932             _ => false,
933         }
934     }
935
936     pub fn is_expr(&self) -> bool {
937         match self.kind {
938             StmtKind::Expr(_) => true,
939             _ => false,
940         }
941     }
942 }
943
944 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
945 pub enum StmtKind {
946     /// A local (let) binding.
947     Local(P<Local>),
948     /// An item definition.
949     Item(P<Item>),
950     /// Expr without trailing semi-colon.
951     Expr(P<Expr>),
952     /// Expr with a trailing semi-colon.
953     Semi(P<Expr>),
954     /// Macro.
955     Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
956 }
957
958 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
959 pub enum MacStmtStyle {
960     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
961     /// `foo!(...);`, `foo![...];`).
962     Semicolon,
963     /// The macro statement had braces (e.g., `foo! { ... }`).
964     Braces,
965     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
966     /// `foo!(...)`). All of these will end up being converted into macro
967     /// expressions.
968     NoBraces,
969 }
970
971 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
972 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
973 pub struct Local {
974     pub id: NodeId,
975     pub pat: P<Pat>,
976     pub ty: Option<P<Ty>>,
977     /// Initializer expression to set the value, if any.
978     pub init: Option<P<Expr>>,
979     pub span: Span,
980     pub attrs: ThinVec<Attribute>,
981 }
982
983 /// An arm of a 'match'.
984 ///
985 /// E.g., `0..=10 => { println!("match!") }` as in
986 ///
987 /// ```
988 /// match 123 {
989 ///     0..=10 => { println!("match!") },
990 ///     _ => { println!("no match!") },
991 /// }
992 /// ```
993 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
994 pub struct Arm {
995     pub attrs: Vec<Attribute>,
996     /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
997     pub pat: P<Pat>,
998     /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
999     pub guard: Option<P<Expr>>,
1000     /// Match arm body.
1001     pub body: P<Expr>,
1002     pub span: Span,
1003     pub id: NodeId,
1004     pub is_placeholder: bool,
1005 }
1006
1007 /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1008 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1009 pub struct Field {
1010     pub attrs: ThinVec<Attribute>,
1011     pub id: NodeId,
1012     pub span: Span,
1013     pub ident: Ident,
1014     pub expr: P<Expr>,
1015     pub is_shorthand: bool,
1016     pub is_placeholder: bool,
1017 }
1018
1019 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1020 pub enum BlockCheckMode {
1021     Default,
1022     Unsafe(UnsafeSource),
1023 }
1024
1025 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1026 pub enum UnsafeSource {
1027     CompilerGenerated,
1028     UserProvided,
1029 }
1030
1031 /// A constant (expression) that's not an item or associated item,
1032 /// but needs its own `DefId` for type-checking, const-eval, etc.
1033 /// These are usually found nested inside types (e.g., array lengths)
1034 /// or expressions (e.g., repeat counts), and also used to define
1035 /// explicit discriminant values for enum variants.
1036 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1037 pub struct AnonConst {
1038     pub id: NodeId,
1039     pub value: P<Expr>,
1040 }
1041
1042 /// An expression.
1043 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1044 pub struct Expr {
1045     pub id: NodeId,
1046     pub kind: ExprKind,
1047     pub span: Span,
1048     pub attrs: ThinVec<Attribute>,
1049 }
1050
1051 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
1052 #[cfg(target_arch = "x86_64")]
1053 rustc_data_structures::static_assert_size!(Expr, 96);
1054
1055 impl Expr {
1056     /// Returns `true` if this expression would be valid somewhere that expects a value;
1057     /// for example, an `if` condition.
1058     pub fn returns(&self) -> bool {
1059         if let ExprKind::Block(ref block, _) = self.kind {
1060             match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
1061                 // Implicit return
1062                 Some(&StmtKind::Expr(_)) => true,
1063                 Some(&StmtKind::Semi(ref expr)) => {
1064                     if let ExprKind::Ret(_) = expr.kind {
1065                         // Last statement is explicit return.
1066                         true
1067                     } else {
1068                         false
1069                     }
1070                 }
1071                 // This is a block that doesn't end in either an implicit or explicit return.
1072                 _ => false,
1073             }
1074         } else {
1075             // This is not a block, it is a value.
1076             true
1077         }
1078     }
1079
1080     pub fn to_bound(&self) -> Option<GenericBound> {
1081         match &self.kind {
1082             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1083                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1084                 TraitBoundModifier::None,
1085             )),
1086             _ => None,
1087         }
1088     }
1089
1090     /// Attempts to reparse as `Ty` (for diagnostic purposes).
1091     pub fn to_ty(&self) -> Option<P<Ty>> {
1092         let kind = match &self.kind {
1093             // Trivial conversions.
1094             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1095             ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1096
1097             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1098
1099             ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr
1100                 .to_ty()
1101                 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1102
1103             ExprKind::Repeat(expr, expr_len) => {
1104                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1105             }
1106
1107             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1108
1109             ExprKind::Tup(exprs) => {
1110                 let tys = exprs
1111                     .iter()
1112                     .map(|expr| expr.to_ty())
1113                     .collect::<Option<Vec<_>>>()?;
1114                 TyKind::Tup(tys)
1115             }
1116
1117             // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
1118             // then type of result is trait object.
1119             // Othewise we don't assume the result type.
1120             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1121                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1122                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1123                 } else {
1124                     return None;
1125                 }
1126             }
1127
1128             // This expression doesn't look like a type syntactically.
1129             _ => return None,
1130         };
1131
1132         Some(P(Ty {
1133             kind,
1134             id: self.id,
1135             span: self.span,
1136         }))
1137     }
1138
1139     pub fn precedence(&self) -> ExprPrecedence {
1140         match self.kind {
1141             ExprKind::Box(_) => ExprPrecedence::Box,
1142             ExprKind::Array(_) => ExprPrecedence::Array,
1143             ExprKind::Call(..) => ExprPrecedence::Call,
1144             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1145             ExprKind::Tup(_) => ExprPrecedence::Tup,
1146             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1147             ExprKind::Unary(..) => ExprPrecedence::Unary,
1148             ExprKind::Lit(_) => ExprPrecedence::Lit,
1149             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1150             ExprKind::Let(..) => ExprPrecedence::Let,
1151             ExprKind::If(..) => ExprPrecedence::If,
1152             ExprKind::While(..) => ExprPrecedence::While,
1153             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1154             ExprKind::Loop(..) => ExprPrecedence::Loop,
1155             ExprKind::Match(..) => ExprPrecedence::Match,
1156             ExprKind::Closure(..) => ExprPrecedence::Closure,
1157             ExprKind::Block(..) => ExprPrecedence::Block,
1158             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1159             ExprKind::Async(..) => ExprPrecedence::Async,
1160             ExprKind::Await(..) => ExprPrecedence::Await,
1161             ExprKind::Assign(..) => ExprPrecedence::Assign,
1162             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1163             ExprKind::Field(..) => ExprPrecedence::Field,
1164             ExprKind::Index(..) => ExprPrecedence::Index,
1165             ExprKind::Range(..) => ExprPrecedence::Range,
1166             ExprKind::Path(..) => ExprPrecedence::Path,
1167             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1168             ExprKind::Break(..) => ExprPrecedence::Break,
1169             ExprKind::Continue(..) => ExprPrecedence::Continue,
1170             ExprKind::Ret(..) => ExprPrecedence::Ret,
1171             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1172             ExprKind::Mac(..) => ExprPrecedence::Mac,
1173             ExprKind::Struct(..) => ExprPrecedence::Struct,
1174             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1175             ExprKind::Paren(..) => ExprPrecedence::Paren,
1176             ExprKind::Try(..) => ExprPrecedence::Try,
1177             ExprKind::Yield(..) => ExprPrecedence::Yield,
1178             ExprKind::Err => ExprPrecedence::Err,
1179         }
1180     }
1181 }
1182
1183 /// Limit types of a range (inclusive or exclusive)
1184 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1185 pub enum RangeLimits {
1186     /// Inclusive at the beginning, exclusive at the end
1187     HalfOpen,
1188     /// Inclusive at the beginning and end
1189     Closed,
1190 }
1191
1192 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1193 pub enum ExprKind {
1194     /// A `box x` expression.
1195     Box(P<Expr>),
1196     /// An array (`[a, b, c, d]`)
1197     Array(Vec<P<Expr>>),
1198     /// A function call
1199     ///
1200     /// The first field resolves to the function itself,
1201     /// and the second field is the list of arguments.
1202     /// This also represents calling the constructor of
1203     /// tuple-like ADTs such as tuple structs and enum variants.
1204     Call(P<Expr>, Vec<P<Expr>>),
1205     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1206     ///
1207     /// The `PathSegment` represents the method name and its generic arguments
1208     /// (within the angle brackets).
1209     /// The first element of the vector of an `Expr` is the expression that evaluates
1210     /// to the object on which the method is being called on (the receiver),
1211     /// and the remaining elements are the rest of the arguments.
1212     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1213     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1214     MethodCall(PathSegment, Vec<P<Expr>>),
1215     /// A tuple (e.g., `(a, b, c, d)`).
1216     Tup(Vec<P<Expr>>),
1217     /// A binary operation (e.g., `a + b`, `a * b`).
1218     Binary(BinOp, P<Expr>, P<Expr>),
1219     /// A unary operation (e.g., `!x`, `*x`).
1220     Unary(UnOp, P<Expr>),
1221     /// A literal (e.g., `1`, `"foo"`).
1222     Lit(Lit),
1223     /// A cast (e.g., `foo as f64`).
1224     Cast(P<Expr>, P<Ty>),
1225     /// A type ascription (e.g., `42: usize`).
1226     Type(P<Expr>, P<Ty>),
1227     /// A `let pat = expr` expression that is only semantically allowed in the condition
1228     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1229     Let(P<Pat>, P<Expr>),
1230     /// An `if` block, with an optional `else` block.
1231     ///
1232     /// `if expr { block } else { expr }`
1233     If(P<Expr>, P<Block>, Option<P<Expr>>),
1234     /// A while loop, with an optional label.
1235     ///
1236     /// `'label: while expr { block }`
1237     While(P<Expr>, P<Block>, Option<Label>),
1238     /// A `for` loop, with an optional label.
1239     ///
1240     /// `'label: for pat in expr { block }`
1241     ///
1242     /// This is desugared to a combination of `loop` and `match` expressions.
1243     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1244     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1245     ///
1246     /// `'label: loop { block }`
1247     Loop(P<Block>, Option<Label>),
1248     /// A `match` block.
1249     Match(P<Expr>, Vec<Arm>),
1250     /// A closure (e.g., `move |a, b, c| a + b + c`).
1251     ///
1252     /// The final span is the span of the argument block `|...|`.
1253     Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1254     /// A block (`'label: { ... }`).
1255     Block(P<Block>, Option<Label>),
1256     /// An async block (`async move { ... }`).
1257     ///
1258     /// The `NodeId` is the `NodeId` for the closure that results from
1259     /// desugaring an async block, just like the NodeId field in the
1260     /// `IsAsync` enum. This is necessary in order to create a def for the
1261     /// closure which can be used as a parent of any child defs. Defs
1262     /// created during lowering cannot be made the parent of any other
1263     /// preexisting defs.
1264     Async(CaptureBy, NodeId, P<Block>),
1265     /// An await expression (`my_future.await`).
1266     Await(P<Expr>),
1267
1268     /// A try block (`try { ... }`).
1269     TryBlock(P<Block>),
1270
1271     /// An assignment (`a = foo()`).
1272     Assign(P<Expr>, P<Expr>),
1273     /// An assignment with an operator.
1274     ///
1275     /// E.g., `a += 1`.
1276     AssignOp(BinOp, P<Expr>, P<Expr>),
1277     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1278     Field(P<Expr>, Ident),
1279     /// An indexing operation (e.g., `foo[2]`).
1280     Index(P<Expr>, P<Expr>),
1281     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1282     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1283
1284     /// Variable reference, possibly containing `::` and/or type
1285     /// parameters (e.g., `foo::bar::<baz>`).
1286     ///
1287     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1288     Path(Option<QSelf>, Path),
1289
1290     /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
1291     AddrOf(BorrowKind, Mutability, P<Expr>),
1292     /// A `break`, with an optional label to break, and an optional expression.
1293     Break(Option<Label>, Option<P<Expr>>),
1294     /// A `continue`, with an optional label.
1295     Continue(Option<Label>),
1296     /// A `return`, with an optional value to be returned.
1297     Ret(Option<P<Expr>>),
1298
1299     /// Output of the `asm!()` macro.
1300     InlineAsm(P<InlineAsm>),
1301
1302     /// A macro invocation; pre-expansion.
1303     Mac(Mac),
1304
1305     /// A struct literal expression.
1306     ///
1307     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1308     /// where `base` is the `Option<Expr>`.
1309     Struct(Path, Vec<Field>, Option<P<Expr>>),
1310
1311     /// An array literal constructed from one repeated element.
1312     ///
1313     /// E.g., `[1; 5]`. The expression is the element to be
1314     /// repeated; the constant is the number of times to repeat it.
1315     Repeat(P<Expr>, AnonConst),
1316
1317     /// No-op: used solely so we can pretty-print faithfully.
1318     Paren(P<Expr>),
1319
1320     /// A try expression (`expr?`).
1321     Try(P<Expr>),
1322
1323     /// A `yield`, with an optional value to be yielded.
1324     Yield(Option<P<Expr>>),
1325
1326     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1327     Err,
1328 }
1329
1330 /// The explicit `Self` type in a "qualified path". The actual
1331 /// path, including the trait and the associated item, is stored
1332 /// separately. `position` represents the index of the associated
1333 /// item qualified with this `Self` type.
1334 ///
1335 /// ```ignore (only-for-syntax-highlight)
1336 /// <Vec<T> as a::b::Trait>::AssociatedItem
1337 ///  ^~~~~     ~~~~~~~~~~~~~~^
1338 ///  ty        position = 3
1339 ///
1340 /// <Vec<T>>::AssociatedItem
1341 ///  ^~~~~    ^
1342 ///  ty       position = 0
1343 /// ```
1344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1345 pub struct QSelf {
1346     pub ty: P<Ty>,
1347
1348     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1349     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1350     /// 0`, this is an empty span.
1351     pub path_span: Span,
1352     pub position: usize,
1353 }
1354
1355 /// A capture clause used in closures and `async` blocks.
1356 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1357 pub enum CaptureBy {
1358     /// `move |x| y + x`.
1359     Value,
1360     /// `move` keyword was not specified.
1361     Ref,
1362 }
1363
1364 /// The movability of a generator / closure literal:
1365 /// whether a generator contains self-references, causing it to be `!Unpin`.
1366 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
1367          RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1368 pub enum Movability {
1369     /// May contain self-references, `!Unpin`.
1370     Static,
1371     /// Must not contain self-references, `Unpin`.
1372     Movable,
1373 }
1374
1375 /// Represents a macro invocation. The `Path` indicates which macro
1376 /// is being invoked, and the vector of token-trees contains the source
1377 /// of the macro invocation.
1378 ///
1379 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1380 /// stored in the enclosing item.
1381 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1382 pub struct Mac {
1383     pub path: Path,
1384     pub delim: MacDelimiter,
1385     pub tts: TokenStream,
1386     pub span: Span,
1387     pub prior_type_ascription: Option<(Span, bool)>,
1388 }
1389
1390 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1391 pub enum MacDelimiter {
1392     Parenthesis,
1393     Bracket,
1394     Brace,
1395 }
1396
1397 impl Mac {
1398     pub fn stream(&self) -> TokenStream {
1399         self.tts.clone()
1400     }
1401 }
1402
1403 impl MacDelimiter {
1404     crate fn to_token(self) -> DelimToken {
1405         match self {
1406             MacDelimiter::Parenthesis => DelimToken::Paren,
1407             MacDelimiter::Bracket => DelimToken::Bracket,
1408             MacDelimiter::Brace => DelimToken::Brace,
1409         }
1410     }
1411 }
1412
1413 /// Represents a macro definition.
1414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1415 pub struct MacroDef {
1416     pub tokens: TokenStream,
1417     /// `true` if macro was defined with `macro_rules`.
1418     pub legacy: bool,
1419 }
1420
1421 impl MacroDef {
1422     pub fn stream(&self) -> TokenStream {
1423         self.tokens.clone().into()
1424     }
1425 }
1426
1427 // Clippy uses Hash and PartialEq
1428 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
1429 pub enum StrStyle {
1430     /// A regular string, like `"foo"`.
1431     Cooked,
1432     /// A raw string, like `r##"foo"##`.
1433     ///
1434     /// The value is the number of `#` symbols used.
1435     Raw(u16),
1436 }
1437
1438 /// An AST literal.
1439 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
1440 pub struct Lit {
1441     /// The original literal token as written in source code.
1442     pub token: token::Lit,
1443     /// The "semantic" representation of the literal lowered from the original tokens.
1444     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1445     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1446     pub kind: LitKind,
1447     pub span: Span,
1448 }
1449
1450 /// Same as `Lit`, but restricted to string literals.
1451 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
1452 pub struct StrLit {
1453     /// The original literal token as written in source code.
1454     pub style: StrStyle,
1455     pub symbol: Symbol,
1456     pub suffix: Option<Symbol>,
1457     pub span: Span,
1458     /// The unescaped "semantic" representation of the literal lowered from the original token.
1459     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1460     pub symbol_unescaped: Symbol,
1461 }
1462
1463 impl StrLit {
1464     crate fn as_lit(&self) -> Lit {
1465         let token_kind = match self.style {
1466             StrStyle::Cooked => token::Str,
1467             StrStyle::Raw(n) => token::StrRaw(n),
1468         };
1469         Lit {
1470             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1471             span: self.span,
1472             kind: LitKind::Str(self.symbol_unescaped, self.style),
1473         }
1474     }
1475 }
1476
1477 // Clippy uses Hash and PartialEq
1478 /// Type of the integer literal based on provided suffix.
1479 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1480 pub enum LitIntType {
1481     /// e.g. `42_i32`.
1482     Signed(IntTy),
1483     /// e.g. `42_u32`.
1484     Unsigned(UintTy),
1485     /// e.g. `42`.
1486     Unsuffixed,
1487 }
1488
1489 /// Type of the float literal based on provided suffix.
1490 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1491 pub enum LitFloatType {
1492     /// A float literal with a suffix (`1f32` or `1E10f32`).
1493     Suffixed(FloatTy),
1494     /// A float literal without a suffix (`1.0 or 1.0E10`).
1495     Unsuffixed,
1496 }
1497
1498 /// Literal kind.
1499 ///
1500 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1501 // Clippy uses Hash and PartialEq
1502 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
1503 pub enum LitKind {
1504     /// A string literal (`"foo"`).
1505     Str(Symbol, StrStyle),
1506     /// A byte string (`b"foo"`).
1507     ByteStr(Lrc<Vec<u8>>),
1508     /// A byte char (`b'f'`).
1509     Byte(u8),
1510     /// A character literal (`'a'`).
1511     Char(char),
1512     /// An integer literal (`1`).
1513     Int(u128, LitIntType),
1514     /// A float literal (`1f64` or `1E10f64`).
1515     Float(Symbol, LitFloatType),
1516     /// A boolean literal.
1517     Bool(bool),
1518     /// Placeholder for a literal that wasn't well-formed in some way.
1519     Err(Symbol),
1520 }
1521
1522 impl LitKind {
1523     /// Returns `true` if this literal is a string.
1524     pub fn is_str(&self) -> bool {
1525         match *self {
1526             LitKind::Str(..) => true,
1527             _ => false,
1528         }
1529     }
1530
1531     /// Returns `true` if this literal is byte literal string.
1532     pub fn is_bytestr(&self) -> bool {
1533         match self {
1534             LitKind::ByteStr(_) => true,
1535             _ => false,
1536         }
1537     }
1538
1539     /// Returns `true` if this is a numeric literal.
1540     pub fn is_numeric(&self) -> bool {
1541         match *self {
1542             LitKind::Int(..) | LitKind::Float(..) => true,
1543             _ => false,
1544         }
1545     }
1546
1547     /// Returns `true` if this literal has no suffix.
1548     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1549     pub fn is_unsuffixed(&self) -> bool {
1550         !self.is_suffixed()
1551     }
1552
1553     /// Returns `true` if this literal has a suffix.
1554     pub fn is_suffixed(&self) -> bool {
1555         match *self {
1556             // suffixed variants
1557             LitKind::Int(_, LitIntType::Signed(..))
1558             | LitKind::Int(_, LitIntType::Unsigned(..))
1559             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1560             // unsuffixed variants
1561             LitKind::Str(..)
1562             | LitKind::ByteStr(..)
1563             | LitKind::Byte(..)
1564             | LitKind::Char(..)
1565             | LitKind::Int(_, LitIntType::Unsuffixed)
1566             | LitKind::Float(_, LitFloatType::Unsuffixed)
1567             | LitKind::Bool(..)
1568             | LitKind::Err(..) => false,
1569         }
1570     }
1571 }
1572
1573 // N.B., If you change this, you'll probably want to change the corresponding
1574 // type structure in `middle/ty.rs` as well.
1575 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1576 pub struct MutTy {
1577     pub ty: P<Ty>,
1578     pub mutbl: Mutability,
1579 }
1580
1581 /// Represents a function's signature in a trait declaration,
1582 /// trait implementation, or free function.
1583 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1584 pub struct FnSig {
1585     pub header: FnHeader,
1586     pub decl: P<FnDecl>,
1587 }
1588
1589 /// Represents an item declaration within a trait declaration,
1590 /// possibly including a default implementation. A trait item is
1591 /// either required (meaning it doesn't have an implementation, just a
1592 /// signature) or provided (meaning it has a default implementation).
1593 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1594 pub struct TraitItem {
1595     pub attrs: Vec<Attribute>,
1596     pub id: NodeId,
1597     pub span: Span,
1598     pub vis: Visibility,
1599     pub ident: Ident,
1600
1601     pub generics: Generics,
1602     pub kind: TraitItemKind,
1603     /// See `Item::tokens` for what this is.
1604     pub tokens: Option<TokenStream>,
1605 }
1606
1607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1608 pub enum TraitItemKind {
1609     Const(P<Ty>, Option<P<Expr>>),
1610     Method(FnSig, Option<P<Block>>),
1611     Type(GenericBounds, Option<P<Ty>>),
1612     Macro(Mac),
1613 }
1614
1615 /// Represents anything within an `impl` block.
1616 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1617 pub struct ImplItem {
1618     pub attrs: Vec<Attribute>,
1619     pub id: NodeId,
1620     pub span: Span,
1621     pub vis: Visibility,
1622     pub ident: Ident,
1623
1624     pub defaultness: Defaultness,
1625     pub generics: Generics,
1626     pub kind: ImplItemKind,
1627     /// See `Item::tokens` for what this is.
1628     pub tokens: Option<TokenStream>,
1629 }
1630
1631 /// Represents various kinds of content within an `impl`.
1632 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1633 pub enum ImplItemKind {
1634     Const(P<Ty>, P<Expr>),
1635     Method(FnSig, P<Block>),
1636     TyAlias(P<Ty>),
1637     Macro(Mac),
1638 }
1639
1640 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1641          RustcEncodable, RustcDecodable, Debug)]
1642 pub enum FloatTy {
1643     F32,
1644     F64,
1645 }
1646
1647 impl FloatTy {
1648     pub fn name_str(self) -> &'static str {
1649         match self {
1650             FloatTy::F32 => "f32",
1651             FloatTy::F64 => "f64",
1652         }
1653     }
1654
1655     pub fn name(self) -> Symbol {
1656         match self {
1657             FloatTy::F32 => sym::f32,
1658             FloatTy::F64 => sym::f64,
1659         }
1660     }
1661
1662     pub fn bit_width(self) -> usize {
1663         match self {
1664             FloatTy::F32 => 32,
1665             FloatTy::F64 => 64,
1666         }
1667     }
1668 }
1669
1670 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1671          RustcEncodable, RustcDecodable, Debug)]
1672 pub enum IntTy {
1673     Isize,
1674     I8,
1675     I16,
1676     I32,
1677     I64,
1678     I128,
1679 }
1680
1681 impl IntTy {
1682     pub fn name_str(&self) -> &'static str {
1683         match *self {
1684             IntTy::Isize => "isize",
1685             IntTy::I8 => "i8",
1686             IntTy::I16 => "i16",
1687             IntTy::I32 => "i32",
1688             IntTy::I64 => "i64",
1689             IntTy::I128 => "i128",
1690         }
1691     }
1692
1693     pub fn name(&self) -> Symbol {
1694         match *self {
1695             IntTy::Isize => sym::isize,
1696             IntTy::I8 => sym::i8,
1697             IntTy::I16 => sym::i16,
1698             IntTy::I32 => sym::i32,
1699             IntTy::I64 => sym::i64,
1700             IntTy::I128 => sym::i128,
1701         }
1702     }
1703
1704     pub fn val_to_string(&self, val: i128) -> String {
1705         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1706         // are parsed as `u128`, so we wouldn't want to print an extra negative
1707         // sign.
1708         format!("{}{}", val as u128, self.name_str())
1709     }
1710
1711     pub fn bit_width(&self) -> Option<usize> {
1712         Some(match *self {
1713             IntTy::Isize => return None,
1714             IntTy::I8 => 8,
1715             IntTy::I16 => 16,
1716             IntTy::I32 => 32,
1717             IntTy::I64 => 64,
1718             IntTy::I128 => 128,
1719         })
1720     }
1721 }
1722
1723 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1724          RustcEncodable, RustcDecodable, Copy, Debug)]
1725 pub enum UintTy {
1726     Usize,
1727     U8,
1728     U16,
1729     U32,
1730     U64,
1731     U128,
1732 }
1733
1734 impl UintTy {
1735     pub fn name_str(&self) -> &'static str {
1736         match *self {
1737             UintTy::Usize => "usize",
1738             UintTy::U8 => "u8",
1739             UintTy::U16 => "u16",
1740             UintTy::U32 => "u32",
1741             UintTy::U64 => "u64",
1742             UintTy::U128 => "u128",
1743         }
1744     }
1745
1746     pub fn name(&self) -> Symbol {
1747         match *self {
1748             UintTy::Usize => sym::usize,
1749             UintTy::U8 => sym::u8,
1750             UintTy::U16 => sym::u16,
1751             UintTy::U32 => sym::u32,
1752             UintTy::U64 => sym::u64,
1753             UintTy::U128 => sym::u128,
1754         }
1755     }
1756
1757     pub fn val_to_string(&self, val: u128) -> String {
1758         format!("{}{}", val, self.name_str())
1759     }
1760
1761     pub fn bit_width(&self) -> Option<usize> {
1762         Some(match *self {
1763             UintTy::Usize => return None,
1764             UintTy::U8 => 8,
1765             UintTy::U16 => 16,
1766             UintTy::U32 => 32,
1767             UintTy::U64 => 64,
1768             UintTy::U128 => 128,
1769         })
1770     }
1771 }
1772
1773 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1774 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1775 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 pub struct AssocTyConstraint {
1777     pub id: NodeId,
1778     pub ident: Ident,
1779     pub kind: AssocTyConstraintKind,
1780     pub span: Span,
1781 }
1782
1783 /// The kinds of an `AssocTyConstraint`.
1784 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1785 pub enum AssocTyConstraintKind {
1786     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1787     Equality {
1788         ty: P<Ty>,
1789     },
1790     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1791     Bound {
1792         bounds: GenericBounds,
1793     },
1794 }
1795
1796 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1797 pub struct Ty {
1798     pub id: NodeId,
1799     pub kind: TyKind,
1800     pub span: Span,
1801 }
1802
1803 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 pub struct BareFnTy {
1805     pub unsafety: Unsafety,
1806     pub ext: Extern,
1807     pub generic_params: Vec<GenericParam>,
1808     pub decl: P<FnDecl>,
1809 }
1810
1811 /// The various kinds of type recognized by the compiler.
1812 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1813 pub enum TyKind {
1814     /// A variable-length slice (`[T]`).
1815     Slice(P<Ty>),
1816     /// A fixed length array (`[T; n]`).
1817     Array(P<Ty>, AnonConst),
1818     /// A raw pointer (`*const T` or `*mut T`).
1819     Ptr(MutTy),
1820     /// A reference (`&'a T` or `&'a mut T`).
1821     Rptr(Option<Lifetime>, MutTy),
1822     /// A bare function (e.g., `fn(usize) -> bool`).
1823     BareFn(P<BareFnTy>),
1824     /// The never type (`!`).
1825     Never,
1826     /// A tuple (`(A, B, C, D,...)`).
1827     Tup(Vec<P<Ty>>),
1828     /// A path (`module::module::...::Type`), optionally
1829     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1830     ///
1831     /// Type parameters are stored in the `Path` itself.
1832     Path(Option<QSelf>, Path),
1833     /// A trait object type `Bound1 + Bound2 + Bound3`
1834     /// where `Bound` is a trait or a lifetime.
1835     TraitObject(GenericBounds, TraitObjectSyntax),
1836     /// An `impl Bound1 + Bound2 + Bound3` type
1837     /// where `Bound` is a trait or a lifetime.
1838     ///
1839     /// The `NodeId` exists to prevent lowering from having to
1840     /// generate `NodeId`s on the fly, which would complicate
1841     /// the generation of opaque `type Foo = impl Trait` items significantly.
1842     ImplTrait(NodeId, GenericBounds),
1843     /// No-op; kept solely so that we can pretty-print faithfully.
1844     Paren(P<Ty>),
1845     /// Unused for now.
1846     Typeof(AnonConst),
1847     /// This means the type should be inferred instead of it having been
1848     /// specified. This can appear anywhere in a type.
1849     Infer,
1850     /// Inferred type of a `self` or `&self` argument in a method.
1851     ImplicitSelf,
1852     /// A macro in the type position.
1853     Mac(Mac),
1854     /// Placeholder for a kind that has failed to be defined.
1855     Err,
1856     /// Placeholder for a `va_list`.
1857     CVarArgs,
1858 }
1859
1860 impl TyKind {
1861     pub fn is_implicit_self(&self) -> bool {
1862         if let TyKind::ImplicitSelf = *self {
1863             true
1864         } else {
1865             false
1866         }
1867     }
1868
1869     pub fn is_unit(&self) -> bool {
1870         if let TyKind::Tup(ref tys) = *self {
1871             tys.is_empty()
1872         } else {
1873             false
1874         }
1875     }
1876
1877     /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1878     /// in lowering to avoid making larger changes there and beyond.
1879     pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1880         match self {
1881             Self::ImplTrait(_, bounds) => Some(bounds),
1882             _ => None,
1883         }
1884     }
1885 }
1886
1887 /// Syntax used to declare a trait object.
1888 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1889 pub enum TraitObjectSyntax {
1890     Dyn,
1891     None,
1892 }
1893
1894 /// Inline assembly dialect.
1895 ///
1896 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1897 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1898 pub enum AsmDialect {
1899     Att,
1900     Intel,
1901 }
1902
1903 /// Inline assembly.
1904 ///
1905 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1906 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1907 pub struct InlineAsmOutput {
1908     pub constraint: Symbol,
1909     pub expr: P<Expr>,
1910     pub is_rw: bool,
1911     pub is_indirect: bool,
1912 }
1913
1914 /// Inline assembly.
1915 ///
1916 /// E.g., `asm!("NOP");`.
1917 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1918 pub struct InlineAsm {
1919     pub asm: Symbol,
1920     pub asm_str_style: StrStyle,
1921     pub outputs: Vec<InlineAsmOutput>,
1922     pub inputs: Vec<(Symbol, P<Expr>)>,
1923     pub clobbers: Vec<Symbol>,
1924     pub volatile: bool,
1925     pub alignstack: bool,
1926     pub dialect: AsmDialect,
1927 }
1928
1929 /// A parameter in a function header.
1930 ///
1931 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1932 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1933 pub struct Param {
1934     pub attrs: ThinVec<Attribute>,
1935     pub ty: P<Ty>,
1936     pub pat: P<Pat>,
1937     pub id: NodeId,
1938     pub span: Span,
1939     pub is_placeholder: bool,
1940 }
1941
1942 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1943 ///
1944 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1945 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1946 pub enum SelfKind {
1947     /// `self`, `mut self`
1948     Value(Mutability),
1949     /// `&'lt self`, `&'lt mut self`
1950     Region(Option<Lifetime>, Mutability),
1951     /// `self: TYPE`, `mut self: TYPE`
1952     Explicit(P<Ty>, Mutability),
1953 }
1954
1955 pub type ExplicitSelf = Spanned<SelfKind>;
1956
1957 impl Param {
1958     /// Attempts to cast parameter to `ExplicitSelf`.
1959     pub fn to_self(&self) -> Option<ExplicitSelf> {
1960         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1961             if ident.name == kw::SelfLower {
1962                 return match self.ty.kind {
1963                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1964                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1965                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1966                     }
1967                     _ => Some(respan(
1968                         self.pat.span.to(self.ty.span),
1969                         SelfKind::Explicit(self.ty.clone(), mutbl),
1970                     )),
1971                 };
1972             }
1973         }
1974         None
1975     }
1976
1977     /// Returns `true` if parameter is `self`.
1978     pub fn is_self(&self) -> bool {
1979         if let PatKind::Ident(_, ident, _) = self.pat.kind {
1980             ident.name == kw::SelfLower
1981         } else {
1982             false
1983         }
1984     }
1985
1986     /// Builds a `Param` object from `ExplicitSelf`.
1987     pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
1988         let span = eself.span.to(eself_ident.span);
1989         let infer_ty = P(Ty {
1990             id: DUMMY_NODE_ID,
1991             kind: TyKind::ImplicitSelf,
1992             span,
1993         });
1994         let param = |mutbl, ty| Param {
1995             attrs,
1996             pat: P(Pat {
1997                 id: DUMMY_NODE_ID,
1998                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1999                 span,
2000             }),
2001             span,
2002             ty,
2003             id: DUMMY_NODE_ID,
2004             is_placeholder: false
2005         };
2006         match eself.node {
2007             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2008             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2009             SelfKind::Region(lt, mutbl) => param(
2010                 Mutability::Immutable,
2011                 P(Ty {
2012                     id: DUMMY_NODE_ID,
2013                     kind: TyKind::Rptr(
2014                         lt,
2015                         MutTy {
2016                             ty: infer_ty,
2017                             mutbl,
2018                         },
2019                     ),
2020                     span,
2021                 }),
2022             ),
2023         }
2024     }
2025 }
2026
2027 /// A signature (not the body) of a function declaration.
2028 ///
2029 /// E.g., `fn foo(bar: baz)`.
2030 ///
2031 /// Please note that it's different from `FnHeader` structure
2032 /// which contains metadata about function safety, asyncness, constness and ABI.
2033 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2034 pub struct FnDecl {
2035     pub inputs: Vec<Param>,
2036     pub output: FunctionRetTy,
2037 }
2038
2039 impl FnDecl {
2040     pub fn get_self(&self) -> Option<ExplicitSelf> {
2041         self.inputs.get(0).and_then(Param::to_self)
2042     }
2043     pub fn has_self(&self) -> bool {
2044         self.inputs.get(0).map_or(false, Param::is_self)
2045     }
2046     pub fn c_variadic(&self) -> bool {
2047         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2048             TyKind::CVarArgs => true,
2049             _ => false,
2050         })
2051     }
2052 }
2053
2054 /// Is the trait definition an auto trait?
2055 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2056 pub enum IsAuto {
2057     Yes,
2058     No,
2059 }
2060
2061 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2062          RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2063 pub enum Unsafety {
2064     Unsafe,
2065     Normal,
2066 }
2067
2068 impl Unsafety {
2069     pub fn prefix_str(&self) -> &'static str {
2070         match self {
2071             Unsafety::Unsafe => "unsafe ",
2072             Unsafety::Normal => "",
2073         }
2074     }
2075 }
2076
2077 impl fmt::Display for Unsafety {
2078     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2079         fmt::Display::fmt(
2080             match *self {
2081                 Unsafety::Normal => "normal",
2082                 Unsafety::Unsafe => "unsafe",
2083             },
2084             f,
2085         )
2086     }
2087 }
2088
2089 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2090 pub enum IsAsync {
2091     Async {
2092         closure_id: NodeId,
2093         return_impl_trait_id: NodeId,
2094     },
2095     NotAsync,
2096 }
2097
2098 impl IsAsync {
2099     pub fn is_async(self) -> bool {
2100         if let IsAsync::Async { .. } = self {
2101             true
2102         } else {
2103             false
2104         }
2105     }
2106
2107     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2108     pub fn opt_return_id(self) -> Option<NodeId> {
2109         match self {
2110             IsAsync::Async {
2111                 return_impl_trait_id,
2112                 ..
2113             } => Some(return_impl_trait_id),
2114             IsAsync::NotAsync => None,
2115         }
2116     }
2117 }
2118
2119 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2120 pub enum Constness {
2121     Const,
2122     NotConst,
2123 }
2124
2125 /// Item defaultness.
2126 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2127 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2128 pub enum Defaultness {
2129     Default,
2130     Final,
2131 }
2132
2133 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2134 pub enum ImplPolarity {
2135     /// `impl Trait for Type`
2136     Positive,
2137     /// `impl !Trait for Type`
2138     Negative,
2139 }
2140
2141 impl fmt::Debug for ImplPolarity {
2142     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2143         match *self {
2144             ImplPolarity::Positive => "positive".fmt(f),
2145             ImplPolarity::Negative => "negative".fmt(f),
2146         }
2147     }
2148 }
2149
2150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2151 pub enum FunctionRetTy {
2152     /// Returns type is not specified.
2153     ///
2154     /// Functions default to `()` and closures default to inference.
2155     /// Span points to where return type would be inserted.
2156     Default(Span),
2157     /// Everything else.
2158     Ty(P<Ty>),
2159 }
2160
2161 impl FunctionRetTy {
2162     pub fn span(&self) -> Span {
2163         match *self {
2164             FunctionRetTy::Default(span) => span,
2165             FunctionRetTy::Ty(ref ty) => ty.span,
2166         }
2167     }
2168 }
2169
2170 /// Module declaration.
2171 ///
2172 /// E.g., `mod foo;` or `mod foo { .. }`.
2173 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2174 pub struct Mod {
2175     /// A span from the first token past `{` to the last token until `}`.
2176     /// For `mod foo;`, the inner span ranges from the first token
2177     /// to the last token in the external file.
2178     pub inner: Span,
2179     pub items: Vec<P<Item>>,
2180     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2181     pub inline: bool,
2182 }
2183
2184 /// Foreign module declaration.
2185 ///
2186 /// E.g., `extern { .. }` or `extern C { .. }`.
2187 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2188 pub struct ForeignMod {
2189     pub abi: Option<StrLit>,
2190     pub items: Vec<ForeignItem>,
2191 }
2192
2193 /// Global inline assembly.
2194 ///
2195 /// Also known as "module-level assembly" or "file-scoped assembly".
2196 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2197 pub struct GlobalAsm {
2198     pub asm: Symbol,
2199 }
2200
2201 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2202 pub struct EnumDef {
2203     pub variants: Vec<Variant>,
2204 }
2205 /// Enum variant.
2206 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2207 pub struct Variant {
2208     /// Attributes of the variant.
2209     pub attrs: Vec<Attribute>,
2210     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2211     pub id: NodeId,
2212     /// Span
2213     pub span: Span,
2214     /// The visibility of the variant. Syntactically accepted but not semantically.
2215     pub vis: Visibility,
2216     /// Name of the variant.
2217     pub ident: Ident,
2218
2219     /// Fields and constructor id of the variant.
2220     pub data: VariantData,
2221     /// Explicit discriminant, e.g., `Foo = 1`.
2222     pub disr_expr: Option<AnonConst>,
2223     /// Is a macro placeholder
2224     pub is_placeholder: bool,
2225 }
2226
2227 /// Part of `use` item to the right of its prefix.
2228 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2229 pub enum UseTreeKind {
2230     /// `use prefix` or `use prefix as rename`
2231     ///
2232     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2233     /// namespace.
2234     Simple(Option<Ident>, NodeId, NodeId),
2235     /// `use prefix::{...}`
2236     Nested(Vec<(UseTree, NodeId)>),
2237     /// `use prefix::*`
2238     Glob,
2239 }
2240
2241 /// A tree of paths sharing common prefixes.
2242 /// Used in `use` items both at top-level and inside of braces in import groups.
2243 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2244 pub struct UseTree {
2245     pub prefix: Path,
2246     pub kind: UseTreeKind,
2247     pub span: Span,
2248 }
2249
2250 impl UseTree {
2251     pub fn ident(&self) -> Ident {
2252         match self.kind {
2253             UseTreeKind::Simple(Some(rename), ..) => rename,
2254             UseTreeKind::Simple(None, ..) => {
2255                 self.prefix
2256                     .segments
2257                     .last()
2258                     .expect("empty prefix in a simple import")
2259                     .ident
2260             }
2261             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2262         }
2263     }
2264 }
2265
2266 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2267 /// are contained as statements within items. These two cases need to be
2268 /// distinguished for pretty-printing.
2269 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2270 pub enum AttrStyle {
2271     Outer,
2272     Inner,
2273 }
2274
2275 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2276 pub struct AttrId(pub usize);
2277
2278 impl Idx for AttrId {
2279     fn new(idx: usize) -> Self {
2280         AttrId(idx)
2281     }
2282     fn index(self) -> usize {
2283         self.0
2284     }
2285 }
2286
2287 impl rustc_serialize::Encodable for AttrId {
2288     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2289         s.emit_unit()
2290     }
2291 }
2292
2293 impl rustc_serialize::Decodable for AttrId {
2294     fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2295         d.read_nil().map(|_| crate::attr::mk_attr_id())
2296     }
2297 }
2298
2299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2300 pub struct AttrItem {
2301     pub path: Path,
2302     pub tokens: TokenStream,
2303 }
2304
2305 /// Metadata associated with an item.
2306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2307 pub struct Attribute {
2308     pub kind: AttrKind,
2309     pub id: AttrId,
2310     /// Denotes if the attribute decorates the following construct (outer)
2311     /// or the construct this attribute is contained within (inner).
2312     pub style: AttrStyle,
2313     pub span: Span,
2314 }
2315
2316 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2317 pub enum AttrKind {
2318     /// A normal attribute.
2319     Normal(AttrItem),
2320
2321     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2322     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2323     /// variant (which is much less compact and thus more expensive).
2324     ///
2325     /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2326     /// for this variant, but this may change in the future.
2327     /// ```
2328     DocComment(Symbol),
2329 }
2330
2331 /// `TraitRef`s appear in impls.
2332 ///
2333 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2334 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2335 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2336 /// same as the impl's `NodeId`).
2337 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2338 pub struct TraitRef {
2339     pub path: Path,
2340     pub ref_id: NodeId,
2341 }
2342
2343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2344 pub struct PolyTraitRef {
2345     /// The `'a` in `<'a> Foo<&'a T>`.
2346     pub bound_generic_params: Vec<GenericParam>,
2347
2348     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2349     pub trait_ref: TraitRef,
2350
2351     pub span: Span,
2352 }
2353
2354 impl PolyTraitRef {
2355     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2356         PolyTraitRef {
2357             bound_generic_params: generic_params,
2358             trait_ref: TraitRef {
2359                 path,
2360                 ref_id: DUMMY_NODE_ID,
2361             },
2362             span,
2363         }
2364     }
2365 }
2366
2367 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2368 pub enum CrateSugar {
2369     /// Source is `pub(crate)`.
2370     PubCrate,
2371
2372     /// Source is (just) `crate`.
2373     JustCrate,
2374 }
2375
2376 pub type Visibility = Spanned<VisibilityKind>;
2377
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2379 pub enum VisibilityKind {
2380     Public,
2381     Crate(CrateSugar),
2382     Restricted { path: P<Path>, id: NodeId },
2383     Inherited,
2384 }
2385
2386 impl VisibilityKind {
2387     pub fn is_pub(&self) -> bool {
2388         if let VisibilityKind::Public = *self {
2389             true
2390         } else {
2391             false
2392         }
2393     }
2394 }
2395
2396 /// Field of a struct.
2397 ///
2398 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2400 pub struct StructField {
2401     pub attrs: Vec<Attribute>,
2402     pub id: NodeId,
2403     pub span: Span,
2404     pub vis: Visibility,
2405     pub ident: Option<Ident>,
2406
2407     pub ty: P<Ty>,
2408     pub is_placeholder: bool,
2409 }
2410
2411 /// Fields and constructor ids of enum variants and structs.
2412 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2413 pub enum VariantData {
2414     /// Struct variant.
2415     ///
2416     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2417     Struct(Vec<StructField>, bool),
2418     /// Tuple variant.
2419     ///
2420     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2421     Tuple(Vec<StructField>, NodeId),
2422     /// Unit variant.
2423     ///
2424     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2425     Unit(NodeId),
2426 }
2427
2428 impl VariantData {
2429     /// Return the fields of this variant.
2430     pub fn fields(&self) -> &[StructField] {
2431         match *self {
2432             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2433             _ => &[],
2434         }
2435     }
2436
2437     /// Return the `NodeId` of this variant's constructor, if it has one.
2438     pub fn ctor_id(&self) -> Option<NodeId> {
2439         match *self {
2440             VariantData::Struct(..) => None,
2441             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2442         }
2443     }
2444 }
2445
2446 /// An item.
2447 ///
2448 /// The name might be a dummy name in case of anonymous items.
2449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2450 pub struct Item {
2451     pub attrs: Vec<Attribute>,
2452     pub id: NodeId,
2453     pub span: Span,
2454     pub vis: Visibility,
2455     pub ident: Ident,
2456
2457     pub kind: ItemKind,
2458
2459     /// Original tokens this item was parsed from. This isn't necessarily
2460     /// available for all items, although over time more and more items should
2461     /// have this be `Some`. Right now this is primarily used for procedural
2462     /// macros, notably custom attributes.
2463     ///
2464     /// Note that the tokens here do not include the outer attributes, but will
2465     /// include inner attributes.
2466     pub tokens: Option<TokenStream>,
2467 }
2468
2469 impl Item {
2470     /// Return the span that encompasses the attributes.
2471     pub fn span_with_attributes(&self) -> Span {
2472         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2473     }
2474 }
2475
2476 /// `extern` qualifier on a function item or function type.
2477 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2478 pub enum Extern {
2479     None,
2480     Implicit,
2481     Explicit(StrLit),
2482 }
2483
2484 impl Extern {
2485     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2486         abi.map_or(Extern::Implicit, Extern::Explicit)
2487     }
2488 }
2489
2490 /// A function header.
2491 ///
2492 /// All the information between the visibility and the name of the function is
2493 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2494 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2495 pub struct FnHeader {
2496     pub unsafety: Unsafety,
2497     pub asyncness: Spanned<IsAsync>,
2498     pub constness: Spanned<Constness>,
2499     pub ext: Extern,
2500 }
2501
2502 impl Default for FnHeader {
2503     fn default() -> FnHeader {
2504         FnHeader {
2505             unsafety: Unsafety::Normal,
2506             asyncness: dummy_spanned(IsAsync::NotAsync),
2507             constness: dummy_spanned(Constness::NotConst),
2508             ext: Extern::None,
2509         }
2510     }
2511 }
2512
2513 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2514 pub enum ItemKind {
2515     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2516     ///
2517     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2518     ExternCrate(Option<Name>),
2519     /// A use declaration item (`use`).
2520     ///
2521     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2522     Use(P<UseTree>),
2523     /// A static item (`static`).
2524     ///
2525     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2526     Static(P<Ty>, Mutability, P<Expr>),
2527     /// A constant item (`const`).
2528     ///
2529     /// E.g., `const FOO: i32 = 42;`.
2530     Const(P<Ty>, P<Expr>),
2531     /// A function declaration (`fn`).
2532     ///
2533     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2534     Fn(FnSig, Generics, P<Block>),
2535     /// A module declaration (`mod`).
2536     ///
2537     /// E.g., `mod foo;` or `mod foo { .. }`.
2538     Mod(Mod),
2539     /// An external module (`extern`).
2540     ///
2541     /// E.g., `extern {}` or `extern "C" {}`.
2542     ForeignMod(ForeignMod),
2543     /// Module-level inline assembly (from `global_asm!()`).
2544     GlobalAsm(P<GlobalAsm>),
2545     /// A type alias (`type`).
2546     ///
2547     /// E.g., `type Foo = Bar<u8>;`.
2548     TyAlias(P<Ty>, Generics),
2549     /// An enum definition (`enum`).
2550     ///
2551     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2552     Enum(EnumDef, Generics),
2553     /// A struct definition (`struct`).
2554     ///
2555     /// E.g., `struct Foo<A> { x: A }`.
2556     Struct(VariantData, Generics),
2557     /// A union definition (`union`).
2558     ///
2559     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2560     Union(VariantData, Generics),
2561     /// A trait declaration (`trait`).
2562     ///
2563     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2564     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2565     /// Trait alias
2566     ///
2567     /// E.g., `trait Foo = Bar + Quux;`.
2568     TraitAlias(Generics, GenericBounds),
2569     /// An implementation.
2570     ///
2571     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2572     Impl(
2573         Unsafety,
2574         ImplPolarity,
2575         Defaultness,
2576         Generics,
2577         Option<TraitRef>, // (optional) trait this impl implements
2578         P<Ty>,            // self
2579         Vec<ImplItem>,
2580     ),
2581     /// A macro invocation.
2582     ///
2583     /// E.g., `foo!(..)`.
2584     Mac(Mac),
2585
2586     /// A macro definition.
2587     MacroDef(MacroDef),
2588 }
2589
2590 impl ItemKind {
2591     pub fn descriptive_variant(&self) -> &str {
2592         match *self {
2593             ItemKind::ExternCrate(..) => "extern crate",
2594             ItemKind::Use(..) => "use",
2595             ItemKind::Static(..) => "static item",
2596             ItemKind::Const(..) => "constant item",
2597             ItemKind::Fn(..) => "function",
2598             ItemKind::Mod(..) => "module",
2599             ItemKind::ForeignMod(..) => "foreign module",
2600             ItemKind::GlobalAsm(..) => "global asm",
2601             ItemKind::TyAlias(..) => "type alias",
2602             ItemKind::Enum(..) => "enum",
2603             ItemKind::Struct(..) => "struct",
2604             ItemKind::Union(..) => "union",
2605             ItemKind::Trait(..) => "trait",
2606             ItemKind::TraitAlias(..) => "trait alias",
2607             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2608         }
2609     }
2610 }
2611
2612 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2613 pub struct ForeignItem {
2614     pub attrs: Vec<Attribute>,
2615     pub id: NodeId,
2616     pub span: Span,
2617     pub vis: Visibility,
2618     pub ident: Ident,
2619
2620     pub kind: ForeignItemKind,
2621 }
2622
2623 /// An item within an `extern` block.
2624 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2625 pub enum ForeignItemKind {
2626     /// A foreign function.
2627     Fn(P<FnDecl>, Generics),
2628     /// A foreign static item (`static ext: u8`).
2629     Static(P<Ty>, Mutability),
2630     /// A foreign type.
2631     Ty,
2632     /// A macro invocation.
2633     Macro(Mac),
2634 }
2635
2636 impl ForeignItemKind {
2637     pub fn descriptive_variant(&self) -> &str {
2638         match *self {
2639             ForeignItemKind::Fn(..) => "foreign function",
2640             ForeignItemKind::Static(..) => "foreign static item",
2641             ForeignItemKind::Ty => "foreign type",
2642             ForeignItemKind::Macro(..) => "macro in foreign module",
2643         }
2644     }
2645 }