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