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