]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Auto merge of #66642 - ecstatic-morse:promotion-in-const, r=eddyb
[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     pub fn normalize(&self, target_width: u32) -> Self {
1723         match self {
1724             IntTy::Isize => match target_width {
1725                 16 => IntTy::I16,
1726                 32 => IntTy::I32,
1727                 64 => IntTy::I64,
1728                 _ => unreachable!(),
1729             },
1730             _ => *self,
1731         }
1732     }
1733 }
1734
1735 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
1736          RustcEncodable, RustcDecodable, Copy, Debug)]
1737 pub enum UintTy {
1738     Usize,
1739     U8,
1740     U16,
1741     U32,
1742     U64,
1743     U128,
1744 }
1745
1746 impl UintTy {
1747     pub fn name_str(&self) -> &'static str {
1748         match *self {
1749             UintTy::Usize => "usize",
1750             UintTy::U8 => "u8",
1751             UintTy::U16 => "u16",
1752             UintTy::U32 => "u32",
1753             UintTy::U64 => "u64",
1754             UintTy::U128 => "u128",
1755         }
1756     }
1757
1758     pub fn name(&self) -> Symbol {
1759         match *self {
1760             UintTy::Usize => sym::usize,
1761             UintTy::U8 => sym::u8,
1762             UintTy::U16 => sym::u16,
1763             UintTy::U32 => sym::u32,
1764             UintTy::U64 => sym::u64,
1765             UintTy::U128 => sym::u128,
1766         }
1767     }
1768
1769     pub fn val_to_string(&self, val: u128) -> String {
1770         format!("{}{}", val, self.name_str())
1771     }
1772
1773     pub fn bit_width(&self) -> Option<usize> {
1774         Some(match *self {
1775             UintTy::Usize => return None,
1776             UintTy::U8 => 8,
1777             UintTy::U16 => 16,
1778             UintTy::U32 => 32,
1779             UintTy::U64 => 64,
1780             UintTy::U128 => 128,
1781         })
1782     }
1783
1784     pub fn normalize(&self, target_width: u32) -> Self {
1785         match self {
1786             UintTy::Usize => match target_width {
1787                 16 => UintTy::U16,
1788                 32 => UintTy::U32,
1789                 64 => UintTy::U64,
1790                 _ => unreachable!(),
1791             },
1792             _ => *self,
1793         }
1794     }
1795 }
1796
1797 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1798 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1799 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1800 pub struct AssocTyConstraint {
1801     pub id: NodeId,
1802     pub ident: Ident,
1803     pub kind: AssocTyConstraintKind,
1804     pub span: Span,
1805 }
1806
1807 /// The kinds of an `AssocTyConstraint`.
1808 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1809 pub enum AssocTyConstraintKind {
1810     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1811     Equality {
1812         ty: P<Ty>,
1813     },
1814     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1815     Bound {
1816         bounds: GenericBounds,
1817     },
1818 }
1819
1820 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1821 pub struct Ty {
1822     pub id: NodeId,
1823     pub kind: TyKind,
1824     pub span: Span,
1825 }
1826
1827 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1828 pub struct BareFnTy {
1829     pub unsafety: Unsafety,
1830     pub ext: Extern,
1831     pub generic_params: Vec<GenericParam>,
1832     pub decl: P<FnDecl>,
1833 }
1834
1835 /// The various kinds of type recognized by the compiler.
1836 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1837 pub enum TyKind {
1838     /// A variable-length slice (`[T]`).
1839     Slice(P<Ty>),
1840     /// A fixed length array (`[T; n]`).
1841     Array(P<Ty>, AnonConst),
1842     /// A raw pointer (`*const T` or `*mut T`).
1843     Ptr(MutTy),
1844     /// A reference (`&'a T` or `&'a mut T`).
1845     Rptr(Option<Lifetime>, MutTy),
1846     /// A bare function (e.g., `fn(usize) -> bool`).
1847     BareFn(P<BareFnTy>),
1848     /// The never type (`!`).
1849     Never,
1850     /// A tuple (`(A, B, C, D,...)`).
1851     Tup(Vec<P<Ty>>),
1852     /// A path (`module::module::...::Type`), optionally
1853     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1854     ///
1855     /// Type parameters are stored in the `Path` itself.
1856     Path(Option<QSelf>, Path),
1857     /// A trait object type `Bound1 + Bound2 + Bound3`
1858     /// where `Bound` is a trait or a lifetime.
1859     TraitObject(GenericBounds, TraitObjectSyntax),
1860     /// An `impl Bound1 + Bound2 + Bound3` type
1861     /// where `Bound` is a trait or a lifetime.
1862     ///
1863     /// The `NodeId` exists to prevent lowering from having to
1864     /// generate `NodeId`s on the fly, which would complicate
1865     /// the generation of opaque `type Foo = impl Trait` items significantly.
1866     ImplTrait(NodeId, GenericBounds),
1867     /// No-op; kept solely so that we can pretty-print faithfully.
1868     Paren(P<Ty>),
1869     /// Unused for now.
1870     Typeof(AnonConst),
1871     /// This means the type should be inferred instead of it having been
1872     /// specified. This can appear anywhere in a type.
1873     Infer,
1874     /// Inferred type of a `self` or `&self` argument in a method.
1875     ImplicitSelf,
1876     /// A macro in the type position.
1877     Mac(Mac),
1878     /// Placeholder for a kind that has failed to be defined.
1879     Err,
1880     /// Placeholder for a `va_list`.
1881     CVarArgs,
1882 }
1883
1884 impl TyKind {
1885     pub fn is_implicit_self(&self) -> bool {
1886         if let TyKind::ImplicitSelf = *self {
1887             true
1888         } else {
1889             false
1890         }
1891     }
1892
1893     pub fn is_unit(&self) -> bool {
1894         if let TyKind::Tup(ref tys) = *self {
1895             tys.is_empty()
1896         } else {
1897             false
1898         }
1899     }
1900
1901     /// HACK(type_alias_impl_trait, Centril): A temporary crutch used
1902     /// in lowering to avoid making larger changes there and beyond.
1903     pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
1904         match self {
1905             Self::ImplTrait(_, bounds) => Some(bounds),
1906             _ => None,
1907         }
1908     }
1909 }
1910
1911 /// Syntax used to declare a trait object.
1912 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1913 pub enum TraitObjectSyntax {
1914     Dyn,
1915     None,
1916 }
1917
1918 /// Inline assembly dialect.
1919 ///
1920 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1921 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
1922 pub enum AsmDialect {
1923     Att,
1924     Intel,
1925 }
1926
1927 /// Inline assembly.
1928 ///
1929 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1930 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1931 pub struct InlineAsmOutput {
1932     pub constraint: Symbol,
1933     pub expr: P<Expr>,
1934     pub is_rw: bool,
1935     pub is_indirect: bool,
1936 }
1937
1938 /// Inline assembly.
1939 ///
1940 /// E.g., `asm!("NOP");`.
1941 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1942 pub struct InlineAsm {
1943     pub asm: Symbol,
1944     pub asm_str_style: StrStyle,
1945     pub outputs: Vec<InlineAsmOutput>,
1946     pub inputs: Vec<(Symbol, P<Expr>)>,
1947     pub clobbers: Vec<Symbol>,
1948     pub volatile: bool,
1949     pub alignstack: bool,
1950     pub dialect: AsmDialect,
1951 }
1952
1953 /// A parameter in a function header.
1954 ///
1955 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1956 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1957 pub struct Param {
1958     pub attrs: ThinVec<Attribute>,
1959     pub ty: P<Ty>,
1960     pub pat: P<Pat>,
1961     pub id: NodeId,
1962     pub span: Span,
1963     pub is_placeholder: bool,
1964 }
1965
1966 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1967 ///
1968 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1969 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1970 pub enum SelfKind {
1971     /// `self`, `mut self`
1972     Value(Mutability),
1973     /// `&'lt self`, `&'lt mut self`
1974     Region(Option<Lifetime>, Mutability),
1975     /// `self: TYPE`, `mut self: TYPE`
1976     Explicit(P<Ty>, Mutability),
1977 }
1978
1979 pub type ExplicitSelf = Spanned<SelfKind>;
1980
1981 impl Param {
1982     /// Attempts to cast parameter to `ExplicitSelf`.
1983     pub fn to_self(&self) -> Option<ExplicitSelf> {
1984         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
1985             if ident.name == kw::SelfLower {
1986                 return match self.ty.kind {
1987                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1988                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
1989                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1990                     }
1991                     _ => Some(respan(
1992                         self.pat.span.to(self.ty.span),
1993                         SelfKind::Explicit(self.ty.clone(), mutbl),
1994                     )),
1995                 };
1996             }
1997         }
1998         None
1999     }
2000
2001     /// Returns `true` if parameter is `self`.
2002     pub fn is_self(&self) -> bool {
2003         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2004             ident.name == kw::SelfLower
2005         } else {
2006             false
2007         }
2008     }
2009
2010     /// Builds a `Param` object from `ExplicitSelf`.
2011     pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2012         let span = eself.span.to(eself_ident.span);
2013         let infer_ty = P(Ty {
2014             id: DUMMY_NODE_ID,
2015             kind: TyKind::ImplicitSelf,
2016             span,
2017         });
2018         let param = |mutbl, ty| Param {
2019             attrs,
2020             pat: P(Pat {
2021                 id: DUMMY_NODE_ID,
2022                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2023                 span,
2024             }),
2025             span,
2026             ty,
2027             id: DUMMY_NODE_ID,
2028             is_placeholder: false
2029         };
2030         match eself.node {
2031             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2032             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2033             SelfKind::Region(lt, mutbl) => param(
2034                 Mutability::Immutable,
2035                 P(Ty {
2036                     id: DUMMY_NODE_ID,
2037                     kind: TyKind::Rptr(
2038                         lt,
2039                         MutTy {
2040                             ty: infer_ty,
2041                             mutbl,
2042                         },
2043                     ),
2044                     span,
2045                 }),
2046             ),
2047         }
2048     }
2049 }
2050
2051 /// A signature (not the body) of a function declaration.
2052 ///
2053 /// E.g., `fn foo(bar: baz)`.
2054 ///
2055 /// Please note that it's different from `FnHeader` structure
2056 /// which contains metadata about function safety, asyncness, constness and ABI.
2057 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2058 pub struct FnDecl {
2059     pub inputs: Vec<Param>,
2060     pub output: FunctionRetTy,
2061 }
2062
2063 impl FnDecl {
2064     pub fn get_self(&self) -> Option<ExplicitSelf> {
2065         self.inputs.get(0).and_then(Param::to_self)
2066     }
2067     pub fn has_self(&self) -> bool {
2068         self.inputs.get(0).map_or(false, Param::is_self)
2069     }
2070     pub fn c_variadic(&self) -> bool {
2071         self.inputs.last().map_or(false, |arg| match arg.ty.kind {
2072             TyKind::CVarArgs => true,
2073             _ => false,
2074         })
2075     }
2076 }
2077
2078 /// Is the trait definition an auto trait?
2079 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2080 pub enum IsAuto {
2081     Yes,
2082     No,
2083 }
2084
2085 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
2086          RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2087 pub enum Unsafety {
2088     Unsafe,
2089     Normal,
2090 }
2091
2092 impl Unsafety {
2093     pub fn prefix_str(&self) -> &'static str {
2094         match self {
2095             Unsafety::Unsafe => "unsafe ",
2096             Unsafety::Normal => "",
2097         }
2098     }
2099 }
2100
2101 impl fmt::Display for Unsafety {
2102     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2103         fmt::Display::fmt(
2104             match *self {
2105                 Unsafety::Normal => "normal",
2106                 Unsafety::Unsafe => "unsafe",
2107             },
2108             f,
2109         )
2110     }
2111 }
2112
2113 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2114 pub enum IsAsync {
2115     Async {
2116         closure_id: NodeId,
2117         return_impl_trait_id: NodeId,
2118     },
2119     NotAsync,
2120 }
2121
2122 impl IsAsync {
2123     pub fn is_async(self) -> bool {
2124         if let IsAsync::Async { .. } = self {
2125             true
2126         } else {
2127             false
2128         }
2129     }
2130
2131     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2132     pub fn opt_return_id(self) -> Option<NodeId> {
2133         match self {
2134             IsAsync::Async {
2135                 return_impl_trait_id,
2136                 ..
2137             } => Some(return_impl_trait_id),
2138             IsAsync::NotAsync => None,
2139         }
2140     }
2141 }
2142
2143 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2144 pub enum Constness {
2145     Const,
2146     NotConst,
2147 }
2148
2149 /// Item defaultness.
2150 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2151 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2152 pub enum Defaultness {
2153     Default,
2154     Final,
2155 }
2156
2157 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
2158 pub enum ImplPolarity {
2159     /// `impl Trait for Type`
2160     Positive,
2161     /// `impl !Trait for Type`
2162     Negative,
2163 }
2164
2165 impl fmt::Debug for ImplPolarity {
2166     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2167         match *self {
2168             ImplPolarity::Positive => "positive".fmt(f),
2169             ImplPolarity::Negative => "negative".fmt(f),
2170         }
2171     }
2172 }
2173
2174 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2175 pub enum FunctionRetTy {
2176     /// Returns type is not specified.
2177     ///
2178     /// Functions default to `()` and closures default to inference.
2179     /// Span points to where return type would be inserted.
2180     Default(Span),
2181     /// Everything else.
2182     Ty(P<Ty>),
2183 }
2184
2185 impl FunctionRetTy {
2186     pub fn span(&self) -> Span {
2187         match *self {
2188             FunctionRetTy::Default(span) => span,
2189             FunctionRetTy::Ty(ref ty) => ty.span,
2190         }
2191     }
2192 }
2193
2194 /// Module declaration.
2195 ///
2196 /// E.g., `mod foo;` or `mod foo { .. }`.
2197 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2198 pub struct Mod {
2199     /// A span from the first token past `{` to the last token until `}`.
2200     /// For `mod foo;`, the inner span ranges from the first token
2201     /// to the last token in the external file.
2202     pub inner: Span,
2203     pub items: Vec<P<Item>>,
2204     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2205     pub inline: bool,
2206 }
2207
2208 /// Foreign module declaration.
2209 ///
2210 /// E.g., `extern { .. }` or `extern C { .. }`.
2211 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2212 pub struct ForeignMod {
2213     pub abi: Option<StrLit>,
2214     pub items: Vec<ForeignItem>,
2215 }
2216
2217 /// Global inline assembly.
2218 ///
2219 /// Also known as "module-level assembly" or "file-scoped assembly".
2220 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2221 pub struct GlobalAsm {
2222     pub asm: Symbol,
2223 }
2224
2225 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2226 pub struct EnumDef {
2227     pub variants: Vec<Variant>,
2228 }
2229 /// Enum variant.
2230 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2231 pub struct Variant {
2232     /// Attributes of the variant.
2233     pub attrs: Vec<Attribute>,
2234     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2235     pub id: NodeId,
2236     /// Span
2237     pub span: Span,
2238     /// The visibility of the variant. Syntactically accepted but not semantically.
2239     pub vis: Visibility,
2240     /// Name of the variant.
2241     pub ident: Ident,
2242
2243     /// Fields and constructor id of the variant.
2244     pub data: VariantData,
2245     /// Explicit discriminant, e.g., `Foo = 1`.
2246     pub disr_expr: Option<AnonConst>,
2247     /// Is a macro placeholder
2248     pub is_placeholder: bool,
2249 }
2250
2251 /// Part of `use` item to the right of its prefix.
2252 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2253 pub enum UseTreeKind {
2254     /// `use prefix` or `use prefix as rename`
2255     ///
2256     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2257     /// namespace.
2258     Simple(Option<Ident>, NodeId, NodeId),
2259     /// `use prefix::{...}`
2260     Nested(Vec<(UseTree, NodeId)>),
2261     /// `use prefix::*`
2262     Glob,
2263 }
2264
2265 /// A tree of paths sharing common prefixes.
2266 /// Used in `use` items both at top-level and inside of braces in import groups.
2267 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2268 pub struct UseTree {
2269     pub prefix: Path,
2270     pub kind: UseTreeKind,
2271     pub span: Span,
2272 }
2273
2274 impl UseTree {
2275     pub fn ident(&self) -> Ident {
2276         match self.kind {
2277             UseTreeKind::Simple(Some(rename), ..) => rename,
2278             UseTreeKind::Simple(None, ..) => {
2279                 self.prefix
2280                     .segments
2281                     .last()
2282                     .expect("empty prefix in a simple import")
2283                     .ident
2284             }
2285             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2286         }
2287     }
2288 }
2289
2290 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2291 /// are contained as statements within items. These two cases need to be
2292 /// distinguished for pretty-printing.
2293 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
2294 pub enum AttrStyle {
2295     Outer,
2296     Inner,
2297 }
2298
2299 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2300 pub struct AttrId(pub usize);
2301
2302 impl Idx for AttrId {
2303     fn new(idx: usize) -> Self {
2304         AttrId(idx)
2305     }
2306     fn index(self) -> usize {
2307         self.0
2308     }
2309 }
2310
2311 impl rustc_serialize::Encodable for AttrId {
2312     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2313         s.emit_unit()
2314     }
2315 }
2316
2317 impl rustc_serialize::Decodable for AttrId {
2318     fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2319         d.read_nil().map(|_| crate::attr::mk_attr_id())
2320     }
2321 }
2322
2323 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2324 pub struct AttrItem {
2325     pub path: Path,
2326     pub tokens: TokenStream,
2327 }
2328
2329 /// Metadata associated with an item.
2330 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2331 pub struct Attribute {
2332     pub kind: AttrKind,
2333     pub id: AttrId,
2334     /// Denotes if the attribute decorates the following construct (outer)
2335     /// or the construct this attribute is contained within (inner).
2336     pub style: AttrStyle,
2337     pub span: Span,
2338 }
2339
2340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2341 pub enum AttrKind {
2342     /// A normal attribute.
2343     Normal(AttrItem),
2344
2345     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2346     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2347     /// variant (which is much less compact and thus more expensive).
2348     ///
2349     /// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
2350     /// for this variant, but this may change in the future.
2351     /// ```
2352     DocComment(Symbol),
2353 }
2354
2355 /// `TraitRef`s appear in impls.
2356 ///
2357 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2358 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2359 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2360 /// same as the impl's `NodeId`).
2361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2362 pub struct TraitRef {
2363     pub path: Path,
2364     pub ref_id: NodeId,
2365 }
2366
2367 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2368 pub struct PolyTraitRef {
2369     /// The `'a` in `<'a> Foo<&'a T>`.
2370     pub bound_generic_params: Vec<GenericParam>,
2371
2372     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2373     pub trait_ref: TraitRef,
2374
2375     pub span: Span,
2376 }
2377
2378 impl PolyTraitRef {
2379     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2380         PolyTraitRef {
2381             bound_generic_params: generic_params,
2382             trait_ref: TraitRef {
2383                 path,
2384                 ref_id: DUMMY_NODE_ID,
2385             },
2386             span,
2387         }
2388     }
2389 }
2390
2391 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
2392 pub enum CrateSugar {
2393     /// Source is `pub(crate)`.
2394     PubCrate,
2395
2396     /// Source is (just) `crate`.
2397     JustCrate,
2398 }
2399
2400 pub type Visibility = Spanned<VisibilityKind>;
2401
2402 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2403 pub enum VisibilityKind {
2404     Public,
2405     Crate(CrateSugar),
2406     Restricted { path: P<Path>, id: NodeId },
2407     Inherited,
2408 }
2409
2410 impl VisibilityKind {
2411     pub fn is_pub(&self) -> bool {
2412         if let VisibilityKind::Public = *self {
2413             true
2414         } else {
2415             false
2416         }
2417     }
2418 }
2419
2420 /// Field of a struct.
2421 ///
2422 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2423 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2424 pub struct StructField {
2425     pub attrs: Vec<Attribute>,
2426     pub id: NodeId,
2427     pub span: Span,
2428     pub vis: Visibility,
2429     pub ident: Option<Ident>,
2430
2431     pub ty: P<Ty>,
2432     pub is_placeholder: bool,
2433 }
2434
2435 /// Fields and constructor ids of enum variants and structs.
2436 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2437 pub enum VariantData {
2438     /// Struct variant.
2439     ///
2440     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2441     Struct(Vec<StructField>, bool),
2442     /// Tuple variant.
2443     ///
2444     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2445     Tuple(Vec<StructField>, NodeId),
2446     /// Unit variant.
2447     ///
2448     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2449     Unit(NodeId),
2450 }
2451
2452 impl VariantData {
2453     /// Return the fields of this variant.
2454     pub fn fields(&self) -> &[StructField] {
2455         match *self {
2456             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2457             _ => &[],
2458         }
2459     }
2460
2461     /// Return the `NodeId` of this variant's constructor, if it has one.
2462     pub fn ctor_id(&self) -> Option<NodeId> {
2463         match *self {
2464             VariantData::Struct(..) => None,
2465             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2466         }
2467     }
2468 }
2469
2470 /// An item.
2471 ///
2472 /// The name might be a dummy name in case of anonymous items.
2473 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2474 pub struct Item {
2475     pub attrs: Vec<Attribute>,
2476     pub id: NodeId,
2477     pub span: Span,
2478     pub vis: Visibility,
2479     pub ident: Ident,
2480
2481     pub kind: ItemKind,
2482
2483     /// Original tokens this item was parsed from. This isn't necessarily
2484     /// available for all items, although over time more and more items should
2485     /// have this be `Some`. Right now this is primarily used for procedural
2486     /// macros, notably custom attributes.
2487     ///
2488     /// Note that the tokens here do not include the outer attributes, but will
2489     /// include inner attributes.
2490     pub tokens: Option<TokenStream>,
2491 }
2492
2493 impl Item {
2494     /// Return the span that encompasses the attributes.
2495     pub fn span_with_attributes(&self) -> Span {
2496         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2497     }
2498 }
2499
2500 /// `extern` qualifier on a function item or function type.
2501 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2502 pub enum Extern {
2503     None,
2504     Implicit,
2505     Explicit(StrLit),
2506 }
2507
2508 impl Extern {
2509     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2510         abi.map_or(Extern::Implicit, Extern::Explicit)
2511     }
2512 }
2513
2514 /// A function header.
2515 ///
2516 /// All the information between the visibility and the name of the function is
2517 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2518 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2519 pub struct FnHeader {
2520     pub unsafety: Unsafety,
2521     pub asyncness: Spanned<IsAsync>,
2522     pub constness: Spanned<Constness>,
2523     pub ext: Extern,
2524 }
2525
2526 impl Default for FnHeader {
2527     fn default() -> FnHeader {
2528         FnHeader {
2529             unsafety: Unsafety::Normal,
2530             asyncness: dummy_spanned(IsAsync::NotAsync),
2531             constness: dummy_spanned(Constness::NotConst),
2532             ext: Extern::None,
2533         }
2534     }
2535 }
2536
2537 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2538 pub enum ItemKind {
2539     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2540     ///
2541     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2542     ExternCrate(Option<Name>),
2543     /// A use declaration item (`use`).
2544     ///
2545     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2546     Use(P<UseTree>),
2547     /// A static item (`static`).
2548     ///
2549     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2550     Static(P<Ty>, Mutability, P<Expr>),
2551     /// A constant item (`const`).
2552     ///
2553     /// E.g., `const FOO: i32 = 42;`.
2554     Const(P<Ty>, P<Expr>),
2555     /// A function declaration (`fn`).
2556     ///
2557     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2558     Fn(FnSig, Generics, P<Block>),
2559     /// A module declaration (`mod`).
2560     ///
2561     /// E.g., `mod foo;` or `mod foo { .. }`.
2562     Mod(Mod),
2563     /// An external module (`extern`).
2564     ///
2565     /// E.g., `extern {}` or `extern "C" {}`.
2566     ForeignMod(ForeignMod),
2567     /// Module-level inline assembly (from `global_asm!()`).
2568     GlobalAsm(P<GlobalAsm>),
2569     /// A type alias (`type`).
2570     ///
2571     /// E.g., `type Foo = Bar<u8>;`.
2572     TyAlias(P<Ty>, Generics),
2573     /// An enum definition (`enum`).
2574     ///
2575     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2576     Enum(EnumDef, Generics),
2577     /// A struct definition (`struct`).
2578     ///
2579     /// E.g., `struct Foo<A> { x: A }`.
2580     Struct(VariantData, Generics),
2581     /// A union definition (`union`).
2582     ///
2583     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2584     Union(VariantData, Generics),
2585     /// A trait declaration (`trait`).
2586     ///
2587     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2588     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2589     /// Trait alias
2590     ///
2591     /// E.g., `trait Foo = Bar + Quux;`.
2592     TraitAlias(Generics, GenericBounds),
2593     /// An implementation.
2594     ///
2595     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2596     Impl(
2597         Unsafety,
2598         ImplPolarity,
2599         Defaultness,
2600         Generics,
2601         Option<TraitRef>, // (optional) trait this impl implements
2602         P<Ty>,            // self
2603         Vec<ImplItem>,
2604     ),
2605     /// A macro invocation.
2606     ///
2607     /// E.g., `foo!(..)`.
2608     Mac(Mac),
2609
2610     /// A macro definition.
2611     MacroDef(MacroDef),
2612 }
2613
2614 impl ItemKind {
2615     pub fn descriptive_variant(&self) -> &str {
2616         match *self {
2617             ItemKind::ExternCrate(..) => "extern crate",
2618             ItemKind::Use(..) => "use",
2619             ItemKind::Static(..) => "static item",
2620             ItemKind::Const(..) => "constant item",
2621             ItemKind::Fn(..) => "function",
2622             ItemKind::Mod(..) => "module",
2623             ItemKind::ForeignMod(..) => "foreign module",
2624             ItemKind::GlobalAsm(..) => "global asm",
2625             ItemKind::TyAlias(..) => "type alias",
2626             ItemKind::Enum(..) => "enum",
2627             ItemKind::Struct(..) => "struct",
2628             ItemKind::Union(..) => "union",
2629             ItemKind::Trait(..) => "trait",
2630             ItemKind::TraitAlias(..) => "trait alias",
2631             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2632         }
2633     }
2634 }
2635
2636 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2637 pub struct ForeignItem {
2638     pub attrs: Vec<Attribute>,
2639     pub id: NodeId,
2640     pub span: Span,
2641     pub vis: Visibility,
2642     pub ident: Ident,
2643
2644     pub kind: ForeignItemKind,
2645 }
2646
2647 /// An item within an `extern` block.
2648 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2649 pub enum ForeignItemKind {
2650     /// A foreign function.
2651     Fn(P<FnDecl>, Generics),
2652     /// A foreign static item (`static ext: u8`).
2653     Static(P<Ty>, Mutability),
2654     /// A foreign type.
2655     Ty,
2656     /// A macro invocation.
2657     Macro(Mac),
2658 }
2659
2660 impl ForeignItemKind {
2661     pub fn descriptive_variant(&self) -> &str {
2662         match *self {
2663             ForeignItemKind::Fn(..) => "foreign function",
2664             ForeignItemKind::Static(..) => "foreign static item",
2665             ForeignItemKind::Ty => "foreign type",
2666             ForeignItemKind::Macro(..) => "macro in foreign module",
2667         }
2668     }
2669 }