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