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