]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ast.rs
Auto merge of #63470 - Mark-Simulacrum:rustc-depdep, 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::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.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     pub span: Span,
613 }
614
615 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
616 pub enum BindingMode {
617     ByRef(Mutability),
618     ByValue(Mutability),
619 }
620
621 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
622 pub enum RangeEnd {
623     Included(RangeSyntax),
624     Excluded,
625 }
626
627 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
628 pub enum RangeSyntax {
629     DotDotDot,
630     DotDotEq,
631 }
632
633 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
634 pub enum PatKind {
635     /// Represents a wildcard pattern (`_`).
636     Wild,
637
638     /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
639     /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
640     /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
641     /// during name resolution.
642     Ident(BindingMode, Ident, Option<P<Pat>>),
643
644     /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
645     /// The `bool` is `true` in the presence of a `..`.
646     Struct(Path, Vec<FieldPat>, /* recovered */ bool),
647
648     /// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
649     TupleStruct(Path, Vec<P<Pat>>),
650
651     /// A possibly qualified path pattern.
652     /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
653     /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
654     /// only legally refer to associated constants.
655     Path(Option<QSelf>, Path),
656
657     /// A tuple pattern (`(a, b)`).
658     Tuple(Vec<P<Pat>>),
659
660     /// A `box` pattern.
661     Box(P<Pat>),
662
663     /// A reference pattern (e.g., `&mut (a, b)`).
664     Ref(P<Pat>, Mutability),
665
666     /// A literal.
667     Lit(P<Expr>),
668
669     /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
670     Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
671
672     /// A slice pattern `[a, b, c]`.
673     Slice(Vec<P<Pat>>),
674
675     /// A rest pattern `..`.
676     ///
677     /// Syntactically it is valid anywhere.
678     ///
679     /// Semantically however, it only has meaning immediately inside:
680     /// - a slice pattern: `[a, .., b]`,
681     /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
682     /// - a tuple pattern: `(a, .., b)`,
683     /// - a tuple struct/variant pattern: `$path(a, .., b)`.
684     ///
685     /// In all of these cases, an additional restriction applies,
686     /// only one rest pattern may occur in the pattern sequences.
687     Rest,
688
689     /// Parentheses in patterns used for grouping (i.e., `(PAT)`).
690     Paren(P<Pat>),
691
692     /// A macro pattern; pre-expansion.
693     Mac(Mac),
694 }
695
696 #[derive(
697     Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
698 )]
699 pub enum Mutability {
700     Mutable,
701     Immutable,
702 }
703
704 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
705 pub enum BinOpKind {
706     /// The `+` operator (addition)
707     Add,
708     /// The `-` operator (subtraction)
709     Sub,
710     /// The `*` operator (multiplication)
711     Mul,
712     /// The `/` operator (division)
713     Div,
714     /// The `%` operator (modulus)
715     Rem,
716     /// The `&&` operator (logical and)
717     And,
718     /// The `||` operator (logical or)
719     Or,
720     /// The `^` operator (bitwise xor)
721     BitXor,
722     /// The `&` operator (bitwise and)
723     BitAnd,
724     /// The `|` operator (bitwise or)
725     BitOr,
726     /// The `<<` operator (shift left)
727     Shl,
728     /// The `>>` operator (shift right)
729     Shr,
730     /// The `==` operator (equality)
731     Eq,
732     /// The `<` operator (less than)
733     Lt,
734     /// The `<=` operator (less than or equal to)
735     Le,
736     /// The `!=` operator (not equal to)
737     Ne,
738     /// The `>=` operator (greater than or equal to)
739     Ge,
740     /// The `>` operator (greater than)
741     Gt,
742 }
743
744 impl BinOpKind {
745     pub fn to_string(&self) -> &'static str {
746         use BinOpKind::*;
747         match *self {
748             Add => "+",
749             Sub => "-",
750             Mul => "*",
751             Div => "/",
752             Rem => "%",
753             And => "&&",
754             Or => "||",
755             BitXor => "^",
756             BitAnd => "&",
757             BitOr => "|",
758             Shl => "<<",
759             Shr => ">>",
760             Eq => "==",
761             Lt => "<",
762             Le => "<=",
763             Ne => "!=",
764             Ge => ">=",
765             Gt => ">",
766         }
767     }
768     pub fn lazy(&self) -> bool {
769         match *self {
770             BinOpKind::And | BinOpKind::Or => true,
771             _ => false,
772         }
773     }
774
775     pub fn is_shift(&self) -> bool {
776         match *self {
777             BinOpKind::Shl | BinOpKind::Shr => true,
778             _ => false,
779         }
780     }
781
782     pub fn is_comparison(&self) -> bool {
783         use BinOpKind::*;
784         match *self {
785             Eq | Lt | Le | Ne | Gt | Ge => true,
786             And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
787         }
788     }
789
790     /// Returns `true` if the binary operator takes its arguments by value
791     pub fn is_by_value(&self) -> bool {
792         !self.is_comparison()
793     }
794 }
795
796 pub type BinOp = Spanned<BinOpKind>;
797
798 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
799 pub enum UnOp {
800     /// The `*` operator for dereferencing
801     Deref,
802     /// The `!` operator for logical inversion
803     Not,
804     /// The `-` operator for negation
805     Neg,
806 }
807
808 impl UnOp {
809     /// Returns `true` if the unary operator takes its argument by value
810     pub fn is_by_value(u: UnOp) -> bool {
811         match u {
812             UnOp::Neg | UnOp::Not => true,
813             _ => false,
814         }
815     }
816
817     pub fn to_string(op: UnOp) -> &'static str {
818         match op {
819             UnOp::Deref => "*",
820             UnOp::Not => "!",
821             UnOp::Neg => "-",
822         }
823     }
824 }
825
826 /// A statement
827 #[derive(Clone, RustcEncodable, RustcDecodable)]
828 pub struct Stmt {
829     pub id: NodeId,
830     pub node: StmtKind,
831     pub span: Span,
832 }
833
834 impl Stmt {
835     pub fn add_trailing_semicolon(mut self) -> Self {
836         self.node = match self.node {
837             StmtKind::Expr(expr) => StmtKind::Semi(expr),
838             StmtKind::Mac(mac) => {
839                 StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
840             }
841             node => node,
842         };
843         self
844     }
845
846     pub fn is_item(&self) -> bool {
847         match self.node {
848             StmtKind::Item(_) => true,
849             _ => false,
850         }
851     }
852
853     pub fn is_expr(&self) -> bool {
854         match self.node {
855             StmtKind::Expr(_) => true,
856             _ => false,
857         }
858     }
859 }
860
861 impl fmt::Debug for Stmt {
862     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863         write!(
864             f,
865             "stmt({}: {})",
866             self.id.to_string(),
867             pprust::stmt_to_string(self)
868         )
869     }
870 }
871
872 #[derive(Clone, RustcEncodable, RustcDecodable)]
873 pub enum StmtKind {
874     /// A local (let) binding.
875     Local(P<Local>),
876
877     /// An item definition.
878     Item(P<Item>),
879
880     /// Expr without trailing semi-colon.
881     Expr(P<Expr>),
882     /// Expr with a trailing semi-colon.
883     Semi(P<Expr>),
884     /// Macro.
885     Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
886 }
887
888 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
889 pub enum MacStmtStyle {
890     /// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
891     /// `foo!(...);`, `foo![...];`).
892     Semicolon,
893     /// The macro statement had braces (e.g., `foo! { ... }`).
894     Braces,
895     /// The macro statement had parentheses or brackets and no semicolon (e.g.,
896     /// `foo!(...)`). All of these will end up being converted into macro
897     /// expressions.
898     NoBraces,
899 }
900
901 /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
902 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
903 pub struct Local {
904     pub pat: P<Pat>,
905     pub ty: Option<P<Ty>>,
906     /// Initializer expression to set the value, if any.
907     pub init: Option<P<Expr>>,
908     pub id: NodeId,
909     pub span: Span,
910     pub attrs: ThinVec<Attribute>,
911 }
912
913 /// An arm of a 'match'.
914 ///
915 /// E.g., `0..=10 => { println!("match!") }` as in
916 ///
917 /// ```
918 /// match 123 {
919 ///     0..=10 => { println!("match!") },
920 ///     _ => { println!("no match!") },
921 /// }
922 /// ```
923 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
924 pub struct Arm {
925     pub attrs: Vec<Attribute>,
926     pub pats: Vec<P<Pat>>,
927     pub guard: Option<P<Expr>>,
928     pub body: P<Expr>,
929     pub span: Span,
930     pub id: NodeId,
931 }
932
933 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
934 pub struct Field {
935     pub ident: Ident,
936     pub expr: P<Expr>,
937     pub span: Span,
938     pub is_shorthand: bool,
939     pub attrs: ThinVec<Attribute>,
940     pub id: NodeId,
941 }
942
943 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
944 pub enum BlockCheckMode {
945     Default,
946     Unsafe(UnsafeSource),
947 }
948
949 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
950 pub enum UnsafeSource {
951     CompilerGenerated,
952     UserProvided,
953 }
954
955 /// A constant (expression) that's not an item or associated item,
956 /// but needs its own `DefId` for type-checking, const-eval, etc.
957 /// These are usually found nested inside types (e.g., array lengths)
958 /// or expressions (e.g., repeat counts), and also used to define
959 /// explicit discriminant values for enum variants.
960 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
961 pub struct AnonConst {
962     pub id: NodeId,
963     pub value: P<Expr>,
964 }
965
966 /// An expression
967 #[derive(Clone, RustcEncodable, RustcDecodable)]
968 pub struct Expr {
969     pub id: NodeId,
970     pub node: ExprKind,
971     pub span: Span,
972     pub attrs: ThinVec<Attribute>,
973 }
974
975 // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
976 #[cfg(target_arch = "x86_64")]
977 static_assert_size!(Expr, 96);
978
979 impl Expr {
980     /// Whether this expression would be valid somewhere that expects a value; for example, an `if`
981     /// condition.
982     pub fn returns(&self) -> bool {
983         if let ExprKind::Block(ref block, _) = self.node {
984             match block.stmts.last().map(|last_stmt| &last_stmt.node) {
985                 // implicit return
986                 Some(&StmtKind::Expr(_)) => true,
987                 Some(&StmtKind::Semi(ref expr)) => {
988                     if let ExprKind::Ret(_) = expr.node {
989                         // last statement is explicit return
990                         true
991                     } else {
992                         false
993                     }
994                 }
995                 // This is a block that doesn't end in either an implicit or explicit return
996                 _ => false,
997             }
998         } else {
999             // This is not a block, it is a value
1000             true
1001         }
1002     }
1003
1004     fn to_bound(&self) -> Option<GenericBound> {
1005         match &self.node {
1006             ExprKind::Path(None, path) => Some(GenericBound::Trait(
1007                 PolyTraitRef::new(Vec::new(), path.clone(), self.span),
1008                 TraitBoundModifier::None,
1009             )),
1010             _ => None,
1011         }
1012     }
1013
1014     pub(super) fn to_ty(&self) -> Option<P<Ty>> {
1015         let node = match &self.node {
1016             ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
1017             ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
1018             ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
1019             ExprKind::AddrOf(mutbl, expr) => expr
1020                 .to_ty()
1021                 .map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
1022             ExprKind::Repeat(expr, expr_len) => {
1023                 expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
1024             }
1025             ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
1026             ExprKind::Tup(exprs) => {
1027                 let tys = exprs
1028                     .iter()
1029                     .map(|expr| expr.to_ty())
1030                     .collect::<Option<Vec<_>>>()?;
1031                 TyKind::Tup(tys)
1032             }
1033             ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
1034                 if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
1035                     TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
1036                 } else {
1037                     return None;
1038                 }
1039             }
1040             _ => return None,
1041         };
1042
1043         Some(P(Ty {
1044             node,
1045             id: self.id,
1046             span: self.span,
1047         }))
1048     }
1049
1050     pub fn precedence(&self) -> ExprPrecedence {
1051         match self.node {
1052             ExprKind::Box(_) => ExprPrecedence::Box,
1053             ExprKind::Array(_) => ExprPrecedence::Array,
1054             ExprKind::Call(..) => ExprPrecedence::Call,
1055             ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
1056             ExprKind::Tup(_) => ExprPrecedence::Tup,
1057             ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
1058             ExprKind::Unary(..) => ExprPrecedence::Unary,
1059             ExprKind::Lit(_) => ExprPrecedence::Lit,
1060             ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
1061             ExprKind::Let(..) => ExprPrecedence::Let,
1062             ExprKind::If(..) => ExprPrecedence::If,
1063             ExprKind::While(..) => ExprPrecedence::While,
1064             ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
1065             ExprKind::Loop(..) => ExprPrecedence::Loop,
1066             ExprKind::Match(..) => ExprPrecedence::Match,
1067             ExprKind::Closure(..) => ExprPrecedence::Closure,
1068             ExprKind::Block(..) => ExprPrecedence::Block,
1069             ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
1070             ExprKind::Async(..) => ExprPrecedence::Async,
1071             ExprKind::Await(..) => ExprPrecedence::Await,
1072             ExprKind::Assign(..) => ExprPrecedence::Assign,
1073             ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
1074             ExprKind::Field(..) => ExprPrecedence::Field,
1075             ExprKind::Index(..) => ExprPrecedence::Index,
1076             ExprKind::Range(..) => ExprPrecedence::Range,
1077             ExprKind::Path(..) => ExprPrecedence::Path,
1078             ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
1079             ExprKind::Break(..) => ExprPrecedence::Break,
1080             ExprKind::Continue(..) => ExprPrecedence::Continue,
1081             ExprKind::Ret(..) => ExprPrecedence::Ret,
1082             ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
1083             ExprKind::Mac(..) => ExprPrecedence::Mac,
1084             ExprKind::Struct(..) => ExprPrecedence::Struct,
1085             ExprKind::Repeat(..) => ExprPrecedence::Repeat,
1086             ExprKind::Paren(..) => ExprPrecedence::Paren,
1087             ExprKind::Try(..) => ExprPrecedence::Try,
1088             ExprKind::Yield(..) => ExprPrecedence::Yield,
1089             ExprKind::Err => ExprPrecedence::Err,
1090         }
1091     }
1092 }
1093
1094 impl fmt::Debug for Expr {
1095     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096         write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
1097     }
1098 }
1099
1100 /// Limit types of a range (inclusive or exclusive)
1101 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1102 pub enum RangeLimits {
1103     /// Inclusive at the beginning, exclusive at the end
1104     HalfOpen,
1105     /// Inclusive at the beginning and end
1106     Closed,
1107 }
1108
1109 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1110 pub enum ExprKind {
1111     /// A `box x` expression.
1112     Box(P<Expr>),
1113     /// An array (`[a, b, c, d]`)
1114     Array(Vec<P<Expr>>),
1115     /// A function call
1116     ///
1117     /// The first field resolves to the function itself,
1118     /// and the second field is the list of arguments.
1119     /// This also represents calling the constructor of
1120     /// tuple-like ADTs such as tuple structs and enum variants.
1121     Call(P<Expr>, Vec<P<Expr>>),
1122     /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
1123     ///
1124     /// The `PathSegment` represents the method name and its generic arguments
1125     /// (within the angle brackets).
1126     /// The first element of the vector of an `Expr` is the expression that evaluates
1127     /// to the object on which the method is being called on (the receiver),
1128     /// and the remaining elements are the rest of the arguments.
1129     /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
1130     /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
1131     MethodCall(PathSegment, Vec<P<Expr>>),
1132     /// A tuple (e.g., `(a, b, c, d)`).
1133     Tup(Vec<P<Expr>>),
1134     /// A binary operation (e.g., `a + b`, `a * b`).
1135     Binary(BinOp, P<Expr>, P<Expr>),
1136     /// A unary operation (e.g., `!x`, `*x`).
1137     Unary(UnOp, P<Expr>),
1138     /// A literal (e.g., `1`, `"foo"`).
1139     Lit(Lit),
1140     /// A cast (e.g., `foo as f64`).
1141     Cast(P<Expr>, P<Ty>),
1142     /// A type ascription (e.g., `42: usize`).
1143     Type(P<Expr>, P<Ty>),
1144     /// A `let pats = expr` expression that is only semantically allowed in the condition
1145     /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
1146     ///
1147     /// The `Vec<P<Pat>>` is for or-patterns at the top level.
1148     /// FIXME(54883): Change this to just `P<Pat>`.
1149     Let(Vec<P<Pat>>, P<Expr>),
1150     /// An `if` block, with an optional `else` block.
1151     ///
1152     /// `if expr { block } else { expr }`
1153     If(P<Expr>, P<Block>, Option<P<Expr>>),
1154     /// A while loop, with an optional label.
1155     ///
1156     /// `'label: while expr { block }`
1157     While(P<Expr>, P<Block>, Option<Label>),
1158     /// A `for` loop, with an optional label.
1159     ///
1160     /// `'label: for pat in expr { block }`
1161     ///
1162     /// This is desugared to a combination of `loop` and `match` expressions.
1163     ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
1164     /// Conditionless loop (can be exited with `break`, `continue`, or `return`).
1165     ///
1166     /// `'label: loop { block }`
1167     Loop(P<Block>, Option<Label>),
1168     /// A `match` block.
1169     Match(P<Expr>, Vec<Arm>),
1170     /// A closure (e.g., `move |a, b, c| a + b + c`).
1171     ///
1172     /// The final span is the span of the argument block `|...|`.
1173     Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
1174     /// A block (`'label: { ... }`).
1175     Block(P<Block>, Option<Label>),
1176     /// An async block (`async move { ... }`).
1177     ///
1178     /// The `NodeId` is the `NodeId` for the closure that results from
1179     /// desugaring an async block, just like the NodeId field in the
1180     /// `IsAsync` enum. This is necessary in order to create a def for the
1181     /// closure which can be used as a parent of any child defs. Defs
1182     /// created during lowering cannot be made the parent of any other
1183     /// preexisting defs.
1184     Async(CaptureBy, NodeId, P<Block>),
1185     /// An await expression (`my_future.await`).
1186     Await(P<Expr>),
1187
1188     /// A try block (`try { ... }`).
1189     TryBlock(P<Block>),
1190
1191     /// An assignment (`a = foo()`).
1192     Assign(P<Expr>, P<Expr>),
1193     /// An assignment with an operator.
1194     ///
1195     /// E.g., `a += 1`.
1196     AssignOp(BinOp, P<Expr>, P<Expr>),
1197     /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
1198     Field(P<Expr>, Ident),
1199     /// An indexing operation (e.g., `foo[2]`).
1200     Index(P<Expr>, P<Expr>),
1201     /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
1202     Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
1203
1204     /// Variable reference, possibly containing `::` and/or type
1205     /// parameters (e.g., `foo::bar::<baz>`).
1206     ///
1207     /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
1208     Path(Option<QSelf>, Path),
1209
1210     /// A referencing operation (`&a` or `&mut a`).
1211     AddrOf(Mutability, P<Expr>),
1212     /// A `break`, with an optional label to break, and an optional expression.
1213     Break(Option<Label>, Option<P<Expr>>),
1214     /// A `continue`, with an optional label.
1215     Continue(Option<Label>),
1216     /// A `return`, with an optional value to be returned.
1217     Ret(Option<P<Expr>>),
1218
1219     /// Output of the `asm!()` macro.
1220     InlineAsm(P<InlineAsm>),
1221
1222     /// A macro invocation; pre-expansion.
1223     Mac(Mac),
1224
1225     /// A struct literal expression.
1226     ///
1227     /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
1228     /// where `base` is the `Option<Expr>`.
1229     Struct(Path, Vec<Field>, Option<P<Expr>>),
1230
1231     /// An array literal constructed from one repeated element.
1232     ///
1233     /// E.g., `[1; 5]`. The expression is the element to be
1234     /// repeated; the constant is the number of times to repeat it.
1235     Repeat(P<Expr>, AnonConst),
1236
1237     /// No-op: used solely so we can pretty-print faithfully.
1238     Paren(P<Expr>),
1239
1240     /// A try expression (`expr?`).
1241     Try(P<Expr>),
1242
1243     /// A `yield`, with an optional value to be yielded.
1244     Yield(Option<P<Expr>>),
1245
1246     /// Placeholder for an expression that wasn't syntactically well formed in some way.
1247     Err,
1248 }
1249
1250 /// The explicit `Self` type in a "qualified path". The actual
1251 /// path, including the trait and the associated item, is stored
1252 /// separately. `position` represents the index of the associated
1253 /// item qualified with this `Self` type.
1254 ///
1255 /// ```ignore (only-for-syntax-highlight)
1256 /// <Vec<T> as a::b::Trait>::AssociatedItem
1257 ///  ^~~~~     ~~~~~~~~~~~~~~^
1258 ///  ty        position = 3
1259 ///
1260 /// <Vec<T>>::AssociatedItem
1261 ///  ^~~~~    ^
1262 ///  ty       position = 0
1263 /// ```
1264 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1265 pub struct QSelf {
1266     pub ty: P<Ty>,
1267
1268     /// The span of `a::b::Trait` in a path like `<Vec<T> as
1269     /// a::b::Trait>::AssociatedItem`; in the case where `position ==
1270     /// 0`, this is an empty span.
1271     pub path_span: Span,
1272     pub position: usize,
1273 }
1274
1275 /// A capture clause.
1276 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1277 pub enum CaptureBy {
1278     Value,
1279     Ref,
1280 }
1281
1282 /// The movability of a generator / closure literal.
1283 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1284 pub enum Movability {
1285     Static,
1286     Movable,
1287 }
1288
1289 /// Represents a macro invocation. The `Path` indicates which macro
1290 /// is being invoked, and the vector of token-trees contains the source
1291 /// of the macro invocation.
1292 ///
1293 /// N.B., the additional ident for a `macro_rules`-style macro is actually
1294 /// stored in the enclosing item.
1295 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1296 pub struct Mac {
1297     pub path: Path,
1298     pub delim: MacDelimiter,
1299     pub tts: TokenStream,
1300     pub span: Span,
1301     pub prior_type_ascription: Option<(Span, bool)>,
1302 }
1303
1304 #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
1305 pub enum MacDelimiter {
1306     Parenthesis,
1307     Bracket,
1308     Brace,
1309 }
1310
1311 impl Mac {
1312     pub fn stream(&self) -> TokenStream {
1313         self.tts.clone()
1314     }
1315 }
1316
1317 impl MacDelimiter {
1318     crate fn to_token(self) -> DelimToken {
1319         match self {
1320             MacDelimiter::Parenthesis => DelimToken::Paren,
1321             MacDelimiter::Bracket => DelimToken::Bracket,
1322             MacDelimiter::Brace => DelimToken::Brace,
1323         }
1324     }
1325 }
1326
1327 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1328 pub struct MacroDef {
1329     pub tokens: TokenStream,
1330     pub legacy: bool,
1331 }
1332
1333 impl MacroDef {
1334     pub fn stream(&self) -> TokenStream {
1335         self.tokens.clone().into()
1336     }
1337 }
1338
1339 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1340 pub enum StrStyle {
1341     /// A regular string, like `"foo"`.
1342     Cooked,
1343     /// A raw string, like `r##"foo"##`.
1344     ///
1345     /// The value is the number of `#` symbols used.
1346     Raw(u16),
1347 }
1348
1349 /// An AST literal.
1350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1351 pub struct Lit {
1352     /// The original literal token as written in source code.
1353     pub token: token::Lit,
1354     /// The "semantic" representation of the literal lowered from the original tokens.
1355     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1356     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1357     pub node: LitKind,
1358     pub span: Span,
1359 }
1360
1361 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
1362 pub enum LitIntType {
1363     Signed(IntTy),
1364     Unsigned(UintTy),
1365     Unsuffixed,
1366 }
1367
1368 /// Literal kind.
1369 ///
1370 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1371 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
1372 pub enum LitKind {
1373     /// A string literal (`"foo"`).
1374     Str(Symbol, StrStyle),
1375     /// A byte string (`b"foo"`).
1376     ByteStr(Lrc<Vec<u8>>),
1377     /// A byte char (`b'f'`).
1378     Byte(u8),
1379     /// A character literal (`'a'`).
1380     Char(char),
1381     /// An integer literal (`1`).
1382     Int(u128, LitIntType),
1383     /// A float literal (`1f64` or `1E10f64`).
1384     Float(Symbol, FloatTy),
1385     /// A float literal without a suffix (`1.0 or 1.0E10`).
1386     FloatUnsuffixed(Symbol),
1387     /// A boolean literal.
1388     Bool(bool),
1389     /// Placeholder for a literal that wasn't well-formed in some way.
1390     Err(Symbol),
1391 }
1392
1393 impl LitKind {
1394     /// Returns `true` if this literal is a string.
1395     pub fn is_str(&self) -> bool {
1396         match *self {
1397             LitKind::Str(..) => true,
1398             _ => false,
1399         }
1400     }
1401
1402     /// Returns `true` if this literal is byte literal string.
1403     pub fn is_bytestr(&self) -> bool {
1404         match self {
1405             LitKind::ByteStr(_) => true,
1406             _ => false,
1407         }
1408     }
1409
1410     /// Returns `true` if this is a numeric literal.
1411     pub fn is_numeric(&self) -> bool {
1412         match *self {
1413             LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
1414             _ => false,
1415         }
1416     }
1417
1418     /// Returns `true` if this literal has no suffix.
1419     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1420     pub fn is_unsuffixed(&self) -> bool {
1421         match *self {
1422             // unsuffixed variants
1423             LitKind::Str(..)
1424             | LitKind::ByteStr(..)
1425             | LitKind::Byte(..)
1426             | LitKind::Char(..)
1427             | LitKind::Int(_, LitIntType::Unsuffixed)
1428             | LitKind::FloatUnsuffixed(..)
1429             | LitKind::Bool(..)
1430             | LitKind::Err(..) => true,
1431             // suffixed variants
1432             LitKind::Int(_, LitIntType::Signed(..))
1433             | LitKind::Int(_, LitIntType::Unsigned(..))
1434             | LitKind::Float(..) => false,
1435         }
1436     }
1437
1438     /// Returns `true` if this literal has a suffix.
1439     pub fn is_suffixed(&self) -> bool {
1440         !self.is_unsuffixed()
1441     }
1442 }
1443
1444 // N.B., If you change this, you'll probably want to change the corresponding
1445 // type structure in `middle/ty.rs` as well.
1446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1447 pub struct MutTy {
1448     pub ty: P<Ty>,
1449     pub mutbl: Mutability,
1450 }
1451
1452 /// Represents a method's signature in a trait declaration,
1453 /// or in an implementation.
1454 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1455 pub struct MethodSig {
1456     pub header: FnHeader,
1457     pub decl: P<FnDecl>,
1458 }
1459
1460 /// Represents an item declaration within a trait declaration,
1461 /// possibly including a default implementation. A trait item is
1462 /// either required (meaning it doesn't have an implementation, just a
1463 /// signature) or provided (meaning it has a default implementation).
1464 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1465 pub struct TraitItem {
1466     pub id: NodeId,
1467     pub ident: Ident,
1468     pub attrs: Vec<Attribute>,
1469     pub generics: Generics,
1470     pub node: TraitItemKind,
1471     pub span: Span,
1472     /// See `Item::tokens` for what this is.
1473     pub tokens: Option<TokenStream>,
1474 }
1475
1476 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1477 pub enum TraitItemKind {
1478     Const(P<Ty>, Option<P<Expr>>),
1479     Method(MethodSig, Option<P<Block>>),
1480     Type(GenericBounds, Option<P<Ty>>),
1481     Macro(Mac),
1482 }
1483
1484 /// Represents anything within an `impl` block.
1485 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1486 pub struct ImplItem {
1487     pub id: NodeId,
1488     pub ident: Ident,
1489     pub vis: Visibility,
1490     pub defaultness: Defaultness,
1491     pub attrs: Vec<Attribute>,
1492     pub generics: Generics,
1493     pub node: ImplItemKind,
1494     pub span: Span,
1495     /// See `Item::tokens` for what this is.
1496     pub tokens: Option<TokenStream>,
1497 }
1498
1499 /// Represents various kinds of content within an `impl`.
1500 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1501 pub enum ImplItemKind {
1502     Const(P<Ty>, P<Expr>),
1503     Method(MethodSig, P<Block>),
1504     TyAlias(P<Ty>),
1505     OpaqueTy(GenericBounds),
1506     Macro(Mac),
1507 }
1508
1509 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1510 pub enum IntTy {
1511     Isize,
1512     I8,
1513     I16,
1514     I32,
1515     I64,
1516     I128,
1517 }
1518
1519 impl fmt::Debug for IntTy {
1520     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1521         fmt::Display::fmt(self, f)
1522     }
1523 }
1524
1525 impl fmt::Display for IntTy {
1526     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527         write!(f, "{}", self.ty_to_string())
1528     }
1529 }
1530
1531 impl IntTy {
1532     pub fn ty_to_string(&self) -> &'static str {
1533         match *self {
1534             IntTy::Isize => "isize",
1535             IntTy::I8 => "i8",
1536             IntTy::I16 => "i16",
1537             IntTy::I32 => "i32",
1538             IntTy::I64 => "i64",
1539             IntTy::I128 => "i128",
1540         }
1541     }
1542
1543     pub fn to_symbol(&self) -> Symbol {
1544         match *self {
1545             IntTy::Isize => sym::isize,
1546             IntTy::I8 => sym::i8,
1547             IntTy::I16 => sym::i16,
1548             IntTy::I32 => sym::i32,
1549             IntTy::I64 => sym::i64,
1550             IntTy::I128 => sym::i128,
1551         }
1552     }
1553
1554     pub fn val_to_string(&self, val: i128) -> String {
1555         // Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
1556         // are parsed as `u128`, so we wouldn't want to print an extra negative
1557         // sign.
1558         format!("{}{}", val as u128, self.ty_to_string())
1559     }
1560
1561     pub fn bit_width(&self) -> Option<usize> {
1562         Some(match *self {
1563             IntTy::Isize => return None,
1564             IntTy::I8 => 8,
1565             IntTy::I16 => 16,
1566             IntTy::I32 => 32,
1567             IntTy::I64 => 64,
1568             IntTy::I128 => 128,
1569         })
1570     }
1571 }
1572
1573 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
1574 pub enum UintTy {
1575     Usize,
1576     U8,
1577     U16,
1578     U32,
1579     U64,
1580     U128,
1581 }
1582
1583 impl UintTy {
1584     pub fn ty_to_string(&self) -> &'static str {
1585         match *self {
1586             UintTy::Usize => "usize",
1587             UintTy::U8 => "u8",
1588             UintTy::U16 => "u16",
1589             UintTy::U32 => "u32",
1590             UintTy::U64 => "u64",
1591             UintTy::U128 => "u128",
1592         }
1593     }
1594
1595     pub fn to_symbol(&self) -> Symbol {
1596         match *self {
1597             UintTy::Usize => sym::usize,
1598             UintTy::U8 => sym::u8,
1599             UintTy::U16 => sym::u16,
1600             UintTy::U32 => sym::u32,
1601             UintTy::U64 => sym::u64,
1602             UintTy::U128 => sym::u128,
1603         }
1604     }
1605
1606     pub fn val_to_string(&self, val: u128) -> String {
1607         format!("{}{}", val, self.ty_to_string())
1608     }
1609
1610     pub fn bit_width(&self) -> Option<usize> {
1611         Some(match *self {
1612             UintTy::Usize => return None,
1613             UintTy::U8 => 8,
1614             UintTy::U16 => 16,
1615             UintTy::U32 => 32,
1616             UintTy::U64 => 64,
1617             UintTy::U128 => 128,
1618         })
1619     }
1620 }
1621
1622 impl fmt::Debug for UintTy {
1623     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1624         fmt::Display::fmt(self, f)
1625     }
1626 }
1627
1628 impl fmt::Display for UintTy {
1629     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1630         write!(f, "{}", self.ty_to_string())
1631     }
1632 }
1633
1634 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1635 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1636 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1637 pub struct AssocTyConstraint {
1638     pub id: NodeId,
1639     pub ident: Ident,
1640     pub kind: AssocTyConstraintKind,
1641     pub span: Span,
1642 }
1643
1644 /// The kinds of an `AssocTyConstraint`.
1645 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1646 pub enum AssocTyConstraintKind {
1647     /// E.g., `A = Bar` in `Foo<A = Bar>`.
1648     Equality {
1649         ty: P<Ty>,
1650     },
1651     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1652     Bound {
1653         bounds: GenericBounds,
1654     },
1655 }
1656
1657 #[derive(Clone, RustcEncodable, RustcDecodable)]
1658 pub struct Ty {
1659     pub id: NodeId,
1660     pub node: TyKind,
1661     pub span: Span,
1662 }
1663
1664 impl fmt::Debug for Ty {
1665     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666         write!(f, "type({})", pprust::ty_to_string(self))
1667     }
1668 }
1669
1670 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1671 pub struct BareFnTy {
1672     pub unsafety: Unsafety,
1673     pub abi: Abi,
1674     pub generic_params: Vec<GenericParam>,
1675     pub decl: P<FnDecl>,
1676 }
1677
1678 /// The various kinds of type recognized by the compiler.
1679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1680 pub enum TyKind {
1681     /// A variable-length slice (`[T]`).
1682     Slice(P<Ty>),
1683     /// A fixed length array (`[T; n]`).
1684     Array(P<Ty>, AnonConst),
1685     /// A raw pointer (`*const T` or `*mut T`).
1686     Ptr(MutTy),
1687     /// A reference (`&'a T` or `&'a mut T`).
1688     Rptr(Option<Lifetime>, MutTy),
1689     /// A bare function (e.g., `fn(usize) -> bool`).
1690     BareFn(P<BareFnTy>),
1691     /// The never type (`!`).
1692     Never,
1693     /// A tuple (`(A, B, C, D,...)`).
1694     Tup(Vec<P<Ty>>),
1695     /// A path (`module::module::...::Type`), optionally
1696     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
1697     ///
1698     /// Type parameters are stored in the `Path` itself.
1699     Path(Option<QSelf>, Path),
1700     /// A trait object type `Bound1 + Bound2 + Bound3`
1701     /// where `Bound` is a trait or a lifetime.
1702     TraitObject(GenericBounds, TraitObjectSyntax),
1703     /// An `impl Bound1 + Bound2 + Bound3` type
1704     /// where `Bound` is a trait or a lifetime.
1705     ///
1706     /// The `NodeId` exists to prevent lowering from having to
1707     /// generate `NodeId`s on the fly, which would complicate
1708     /// the generation of opaque `type Foo = impl Trait` items significantly.
1709     ImplTrait(NodeId, GenericBounds),
1710     /// No-op; kept solely so that we can pretty-print faithfully.
1711     Paren(P<Ty>),
1712     /// Unused for now.
1713     Typeof(AnonConst),
1714     /// This means the type should be inferred instead of it having been
1715     /// specified. This can appear anywhere in a type.
1716     Infer,
1717     /// Inferred type of a `self` or `&self` argument in a method.
1718     ImplicitSelf,
1719     /// A macro in the type position.
1720     Mac(Mac),
1721     /// Placeholder for a kind that has failed to be defined.
1722     Err,
1723     /// Placeholder for a `va_list`.
1724     CVarArgs,
1725 }
1726
1727 impl TyKind {
1728     pub fn is_implicit_self(&self) -> bool {
1729         if let TyKind::ImplicitSelf = *self {
1730             true
1731         } else {
1732             false
1733         }
1734     }
1735
1736     pub fn is_unit(&self) -> bool {
1737         if let TyKind::Tup(ref tys) = *self {
1738             tys.is_empty()
1739         } else {
1740             false
1741         }
1742     }
1743 }
1744
1745 /// Syntax used to declare a trait object.
1746 #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1747 pub enum TraitObjectSyntax {
1748     Dyn,
1749     None,
1750 }
1751
1752 /// Inline assembly dialect.
1753 ///
1754 /// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1755 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
1756 pub enum AsmDialect {
1757     Att,
1758     Intel,
1759 }
1760
1761 /// Inline assembly.
1762 ///
1763 /// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
1764 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1765 pub struct InlineAsmOutput {
1766     pub constraint: Symbol,
1767     pub expr: P<Expr>,
1768     pub is_rw: bool,
1769     pub is_indirect: bool,
1770 }
1771
1772 /// Inline assembly.
1773 ///
1774 /// E.g., `asm!("NOP");`.
1775 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 pub struct InlineAsm {
1777     pub asm: Symbol,
1778     pub asm_str_style: StrStyle,
1779     pub outputs: Vec<InlineAsmOutput>,
1780     pub inputs: Vec<(Symbol, P<Expr>)>,
1781     pub clobbers: Vec<Symbol>,
1782     pub volatile: bool,
1783     pub alignstack: bool,
1784     pub dialect: AsmDialect,
1785     pub ctxt: SyntaxContext,
1786 }
1787
1788 /// An argument in a function header.
1789 ///
1790 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
1791 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1792 pub struct Arg {
1793     pub attrs: ThinVec<Attribute>,
1794     pub ty: P<Ty>,
1795     pub pat: P<Pat>,
1796     pub id: NodeId,
1797     pub span: Span,
1798 }
1799
1800 /// Alternative representation for `Arg`s describing `self` parameter of methods.
1801 ///
1802 /// E.g., `&mut self` as in `fn foo(&mut self)`.
1803 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1804 pub enum SelfKind {
1805     /// `self`, `mut self`
1806     Value(Mutability),
1807     /// `&'lt self`, `&'lt mut self`
1808     Region(Option<Lifetime>, Mutability),
1809     /// `self: TYPE`, `mut self: TYPE`
1810     Explicit(P<Ty>, Mutability),
1811 }
1812
1813 pub type ExplicitSelf = Spanned<SelfKind>;
1814
1815 impl Arg {
1816     pub fn to_self(&self) -> Option<ExplicitSelf> {
1817         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
1818             if ident.name == kw::SelfLower {
1819                 return match self.ty.node {
1820                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
1821                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
1822                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
1823                     }
1824                     _ => Some(respan(
1825                         self.pat.span.to(self.ty.span),
1826                         SelfKind::Explicit(self.ty.clone(), mutbl),
1827                     )),
1828                 };
1829             }
1830         }
1831         None
1832     }
1833
1834     pub fn is_self(&self) -> bool {
1835         if let PatKind::Ident(_, ident, _) = self.pat.node {
1836             ident.name == kw::SelfLower
1837         } else {
1838             false
1839         }
1840     }
1841
1842     pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Arg {
1843         let span = eself.span.to(eself_ident.span);
1844         let infer_ty = P(Ty {
1845             id: DUMMY_NODE_ID,
1846             node: TyKind::ImplicitSelf,
1847             span,
1848         });
1849         let arg = |mutbl, ty| Arg {
1850             attrs,
1851             pat: P(Pat {
1852                 id: DUMMY_NODE_ID,
1853                 node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
1854                 span,
1855             }),
1856             span,
1857             ty,
1858             id: DUMMY_NODE_ID,
1859         };
1860         match eself.node {
1861             SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
1862             SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
1863             SelfKind::Region(lt, mutbl) => arg(
1864                 Mutability::Immutable,
1865                 P(Ty {
1866                     id: DUMMY_NODE_ID,
1867                     node: TyKind::Rptr(
1868                         lt,
1869                         MutTy {
1870                             ty: infer_ty,
1871                             mutbl,
1872                         },
1873                     ),
1874                     span,
1875                 }),
1876             ),
1877         }
1878     }
1879 }
1880
1881 /// A header (not the body) of a function declaration.
1882 ///
1883 /// E.g., `fn foo(bar: baz)`.
1884 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1885 pub struct FnDecl {
1886     pub inputs: Vec<Arg>,
1887     pub output: FunctionRetTy,
1888     pub c_variadic: bool,
1889 }
1890
1891 impl FnDecl {
1892     pub fn get_self(&self) -> Option<ExplicitSelf> {
1893         self.inputs.get(0).and_then(Arg::to_self)
1894     }
1895     pub fn has_self(&self) -> bool {
1896         self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
1897     }
1898 }
1899
1900 /// Is the trait definition an auto trait?
1901 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1902 pub enum IsAuto {
1903     Yes,
1904     No,
1905 }
1906
1907 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1908 pub enum Unsafety {
1909     Unsafe,
1910     Normal,
1911 }
1912
1913 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum IsAsync {
1915     Async {
1916         closure_id: NodeId,
1917         return_impl_trait_id: NodeId,
1918     },
1919     NotAsync,
1920 }
1921
1922 impl IsAsync {
1923     pub fn is_async(self) -> bool {
1924         if let IsAsync::Async { .. } = self {
1925             true
1926         } else {
1927             false
1928         }
1929     }
1930
1931     /// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
1932     pub fn opt_return_id(self) -> Option<NodeId> {
1933         match self {
1934             IsAsync::Async {
1935                 return_impl_trait_id,
1936                 ..
1937             } => Some(return_impl_trait_id),
1938             IsAsync::NotAsync => None,
1939         }
1940     }
1941 }
1942
1943 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1944 pub enum Constness {
1945     Const,
1946     NotConst,
1947 }
1948
1949 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
1950 pub enum Defaultness {
1951     Default,
1952     Final,
1953 }
1954
1955 impl fmt::Display for Unsafety {
1956     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1957         fmt::Display::fmt(
1958             match *self {
1959                 Unsafety::Normal => "normal",
1960                 Unsafety::Unsafe => "unsafe",
1961             },
1962             f,
1963         )
1964     }
1965 }
1966
1967 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable)]
1968 pub enum ImplPolarity {
1969     /// `impl Trait for Type`
1970     Positive,
1971     /// `impl !Trait for Type`
1972     Negative,
1973 }
1974
1975 impl fmt::Debug for ImplPolarity {
1976     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1977         match *self {
1978             ImplPolarity::Positive => "positive".fmt(f),
1979             ImplPolarity::Negative => "negative".fmt(f),
1980         }
1981     }
1982 }
1983
1984 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1985 pub enum FunctionRetTy {
1986     /// Returns type is not specified.
1987     ///
1988     /// Functions default to `()` and closures default to inference.
1989     /// Span points to where return type would be inserted.
1990     Default(Span),
1991     /// Everything else.
1992     Ty(P<Ty>),
1993 }
1994
1995 impl FunctionRetTy {
1996     pub fn span(&self) -> Span {
1997         match *self {
1998             FunctionRetTy::Default(span) => span,
1999             FunctionRetTy::Ty(ref ty) => ty.span,
2000         }
2001     }
2002 }
2003
2004 /// Module declaration.
2005 ///
2006 /// E.g., `mod foo;` or `mod foo { .. }`.
2007 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2008 pub struct Mod {
2009     /// A span from the first token past `{` to the last token until `}`.
2010     /// For `mod foo;`, the inner span ranges from the first token
2011     /// to the last token in the external file.
2012     pub inner: Span,
2013     pub items: Vec<P<Item>>,
2014     /// `true` for `mod foo { .. }`; `false` for `mod foo;`.
2015     pub inline: bool,
2016 }
2017
2018 /// Foreign module declaration.
2019 ///
2020 /// E.g., `extern { .. }` or `extern C { .. }`.
2021 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2022 pub struct ForeignMod {
2023     pub abi: Abi,
2024     pub items: Vec<ForeignItem>,
2025 }
2026
2027 /// Global inline assembly.
2028 ///
2029 /// Also known as "module-level assembly" or "file-scoped assembly".
2030 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
2031 pub struct GlobalAsm {
2032     pub asm: Symbol,
2033     pub ctxt: SyntaxContext,
2034 }
2035
2036 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2037 pub struct EnumDef {
2038     pub variants: Vec<Variant>,
2039 }
2040
2041 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2042 pub struct Variant {
2043     /// Name of the variant.
2044     pub ident: Ident,
2045     /// Attributes of the variant.
2046     pub attrs: Vec<Attribute>,
2047     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2048     pub id: NodeId,
2049     /// Fields and constructor id of the variant.
2050     pub data: VariantData,
2051     /// Explicit discriminant, e.g., `Foo = 1`.
2052     pub disr_expr: Option<AnonConst>,
2053     /// Span
2054     pub span: Span,
2055 }
2056
2057 /// Part of `use` item to the right of its prefix.
2058 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2059 pub enum UseTreeKind {
2060     /// `use prefix` or `use prefix as rename`
2061     ///
2062     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2063     /// namespace.
2064     Simple(Option<Ident>, NodeId, NodeId),
2065     /// `use prefix::{...}`
2066     Nested(Vec<(UseTree, NodeId)>),
2067     /// `use prefix::*`
2068     Glob,
2069 }
2070
2071 /// A tree of paths sharing common prefixes.
2072 /// Used in `use` items both at top-level and inside of braces in import groups.
2073 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2074 pub struct UseTree {
2075     pub prefix: Path,
2076     pub kind: UseTreeKind,
2077     pub span: Span,
2078 }
2079
2080 impl UseTree {
2081     pub fn ident(&self) -> Ident {
2082         match self.kind {
2083             UseTreeKind::Simple(Some(rename), ..) => rename,
2084             UseTreeKind::Simple(None, ..) => {
2085                 self.prefix
2086                     .segments
2087                     .last()
2088                     .expect("empty prefix in a simple import")
2089                     .ident
2090             }
2091             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2092         }
2093     }
2094 }
2095
2096 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2097 /// are contained as statements within items. These two cases need to be
2098 /// distinguished for pretty-printing.
2099 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
2100 pub enum AttrStyle {
2101     Outer,
2102     Inner,
2103 }
2104
2105 #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
2106 pub struct AttrId(pub usize);
2107
2108 impl Idx for AttrId {
2109     fn new(idx: usize) -> Self {
2110         AttrId(idx)
2111     }
2112     fn index(self) -> usize {
2113         self.0
2114     }
2115 }
2116
2117 impl rustc_serialize::Encodable for AttrId {
2118     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
2119         s.emit_unit()
2120     }
2121 }
2122
2123 impl rustc_serialize::Decodable for AttrId {
2124     fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
2125         d.read_nil().map(|_| crate::attr::mk_attr_id())
2126     }
2127 }
2128
2129 /// Metadata associated with an item.
2130 /// Doc-comments are promoted to attributes that have `is_sugared_doc = true`.
2131 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2132 pub struct Attribute {
2133     pub id: AttrId,
2134     pub style: AttrStyle,
2135     pub path: Path,
2136     pub tokens: TokenStream,
2137     pub is_sugared_doc: bool,
2138     pub span: Span,
2139 }
2140
2141 /// `TraitRef`s appear in impls.
2142 ///
2143 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2144 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2145 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2146 /// same as the impl's `NodeId`).
2147 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2148 pub struct TraitRef {
2149     pub path: Path,
2150     pub ref_id: NodeId,
2151 }
2152
2153 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2154 pub struct PolyTraitRef {
2155     /// The `'a` in `<'a> Foo<&'a T>`.
2156     pub bound_generic_params: Vec<GenericParam>,
2157
2158     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2159     pub trait_ref: TraitRef,
2160
2161     pub span: Span,
2162 }
2163
2164 impl PolyTraitRef {
2165     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2166         PolyTraitRef {
2167             bound_generic_params: generic_params,
2168             trait_ref: TraitRef {
2169                 path,
2170                 ref_id: DUMMY_NODE_ID,
2171             },
2172             span,
2173         }
2174     }
2175 }
2176
2177 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
2178 pub enum CrateSugar {
2179     /// Source is `pub(crate)`.
2180     PubCrate,
2181
2182     /// Source is (just) `crate`.
2183     JustCrate,
2184 }
2185
2186 pub type Visibility = Spanned<VisibilityKind>;
2187
2188 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2189 pub enum VisibilityKind {
2190     Public,
2191     Crate(CrateSugar),
2192     Restricted { path: P<Path>, id: NodeId },
2193     Inherited,
2194 }
2195
2196 impl VisibilityKind {
2197     pub fn is_pub(&self) -> bool {
2198         if let VisibilityKind::Public = *self {
2199             true
2200         } else {
2201             false
2202         }
2203     }
2204 }
2205
2206 /// Field of a struct.
2207 ///
2208 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2209 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2210 pub struct StructField {
2211     pub span: Span,
2212     pub ident: Option<Ident>,
2213     pub vis: Visibility,
2214     pub id: NodeId,
2215     pub ty: P<Ty>,
2216     pub attrs: Vec<Attribute>,
2217 }
2218
2219 /// Fields and constructor ids of enum variants and structs.
2220 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2221 pub enum VariantData {
2222     /// Struct variant.
2223     ///
2224     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2225     Struct(Vec<StructField>, bool),
2226     /// Tuple variant.
2227     ///
2228     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2229     Tuple(Vec<StructField>, NodeId),
2230     /// Unit variant.
2231     ///
2232     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2233     Unit(NodeId),
2234 }
2235
2236 impl VariantData {
2237     /// Return the fields of this variant.
2238     pub fn fields(&self) -> &[StructField] {
2239         match *self {
2240             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2241             _ => &[],
2242         }
2243     }
2244
2245     /// Return the `NodeId` of this variant's constructor, if it has one.
2246     pub fn ctor_id(&self) -> Option<NodeId> {
2247         match *self {
2248             VariantData::Struct(..) => None,
2249             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2250         }
2251     }
2252 }
2253
2254 /// An item.
2255 ///
2256 /// The name might be a dummy name in case of anonymous items.
2257 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2258 pub struct Item {
2259     pub ident: Ident,
2260     pub attrs: Vec<Attribute>,
2261     pub id: NodeId,
2262     pub node: ItemKind,
2263     pub vis: Visibility,
2264     pub span: Span,
2265
2266     /// Original tokens this item was parsed from. This isn't necessarily
2267     /// available for all items, although over time more and more items should
2268     /// have this be `Some`. Right now this is primarily used for procedural
2269     /// macros, notably custom attributes.
2270     ///
2271     /// Note that the tokens here do not include the outer attributes, but will
2272     /// include inner attributes.
2273     pub tokens: Option<TokenStream>,
2274 }
2275
2276 impl Item {
2277     /// Return the span that encompasses the attributes.
2278     pub fn span_with_attributes(&self) -> Span {
2279         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2280     }
2281 }
2282
2283 /// A function header.
2284 ///
2285 /// All the information between the visibility and the name of the function is
2286 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2287 #[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
2288 pub struct FnHeader {
2289     pub unsafety: Unsafety,
2290     pub asyncness: Spanned<IsAsync>,
2291     pub constness: Spanned<Constness>,
2292     pub abi: Abi,
2293 }
2294
2295 impl Default for FnHeader {
2296     fn default() -> FnHeader {
2297         FnHeader {
2298             unsafety: Unsafety::Normal,
2299             asyncness: dummy_spanned(IsAsync::NotAsync),
2300             constness: dummy_spanned(Constness::NotConst),
2301             abi: Abi::Rust,
2302         }
2303     }
2304 }
2305
2306 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2307 pub enum ItemKind {
2308     /// An `extern crate` item, with optional *original* crate name if the crate was renamed.
2309     ///
2310     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2311     ExternCrate(Option<Name>),
2312     /// A use declaration (`use` or `pub use`) item.
2313     ///
2314     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2315     Use(P<UseTree>),
2316     /// A static item (`static` or `pub static`).
2317     ///
2318     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2319     Static(P<Ty>, Mutability, P<Expr>),
2320     /// A constant item (`const` or `pub const`).
2321     ///
2322     /// E.g., `const FOO: i32 = 42;`.
2323     Const(P<Ty>, P<Expr>),
2324     /// A function declaration (`fn` or `pub fn`).
2325     ///
2326     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2327     Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
2328     /// A module declaration (`mod` or `pub mod`).
2329     ///
2330     /// E.g., `mod foo;` or `mod foo { .. }`.
2331     Mod(Mod),
2332     /// An external module (`extern` or `pub extern`).
2333     ///
2334     /// E.g., `extern {}` or `extern "C" {}`.
2335     ForeignMod(ForeignMod),
2336     /// Module-level inline assembly (from `global_asm!()`).
2337     GlobalAsm(P<GlobalAsm>),
2338     /// A type alias (`type` or `pub type`).
2339     ///
2340     /// E.g., `type Foo = Bar<u8>;`.
2341     TyAlias(P<Ty>, Generics),
2342     /// An opaque `impl Trait` type alias.
2343     ///
2344     /// E.g., `type Foo = impl Bar + Boo;`.
2345     OpaqueTy(GenericBounds, Generics),
2346     /// An enum definition (`enum` or `pub enum`).
2347     ///
2348     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2349     Enum(EnumDef, Generics),
2350     /// A struct definition (`struct` or `pub struct`).
2351     ///
2352     /// E.g., `struct Foo<A> { x: A }`.
2353     Struct(VariantData, Generics),
2354     /// A union definition (`union` or `pub union`).
2355     ///
2356     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2357     Union(VariantData, Generics),
2358     /// A Trait declaration (`trait` or `pub trait`).
2359     ///
2360     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2361     Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
2362     /// Trait alias
2363     ///
2364     /// E.g., `trait Foo = Bar + Quux;`.
2365     TraitAlias(Generics, GenericBounds),
2366     /// An implementation.
2367     ///
2368     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2369     Impl(
2370         Unsafety,
2371         ImplPolarity,
2372         Defaultness,
2373         Generics,
2374         Option<TraitRef>, // (optional) trait this impl implements
2375         P<Ty>,            // self
2376         Vec<ImplItem>,
2377     ),
2378     /// A macro invocation.
2379     ///
2380     /// E.g., `macro_rules! foo { .. }` or `foo!(..)`.
2381     Mac(Mac),
2382
2383     /// A macro definition.
2384     MacroDef(MacroDef),
2385 }
2386
2387 impl ItemKind {
2388     pub fn descriptive_variant(&self) -> &str {
2389         match *self {
2390             ItemKind::ExternCrate(..) => "extern crate",
2391             ItemKind::Use(..) => "use",
2392             ItemKind::Static(..) => "static item",
2393             ItemKind::Const(..) => "constant item",
2394             ItemKind::Fn(..) => "function",
2395             ItemKind::Mod(..) => "module",
2396             ItemKind::ForeignMod(..) => "foreign module",
2397             ItemKind::GlobalAsm(..) => "global asm",
2398             ItemKind::TyAlias(..) => "type alias",
2399             ItemKind::OpaqueTy(..) => "opaque type",
2400             ItemKind::Enum(..) => "enum",
2401             ItemKind::Struct(..) => "struct",
2402             ItemKind::Union(..) => "union",
2403             ItemKind::Trait(..) => "trait",
2404             ItemKind::TraitAlias(..) => "trait alias",
2405             ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
2406         }
2407     }
2408 }
2409
2410 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2411 pub struct ForeignItem {
2412     pub ident: Ident,
2413     pub attrs: Vec<Attribute>,
2414     pub node: ForeignItemKind,
2415     pub id: NodeId,
2416     pub span: Span,
2417     pub vis: Visibility,
2418 }
2419
2420 /// An item within an `extern` block.
2421 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2422 pub enum ForeignItemKind {
2423     /// A foreign function.
2424     Fn(P<FnDecl>, Generics),
2425     /// A foreign static item (`static ext: u8`).
2426     Static(P<Ty>, Mutability),
2427     /// A foreign type.
2428     Ty,
2429     /// A macro invocation.
2430     Macro(Mac),
2431 }
2432
2433 impl ForeignItemKind {
2434     pub fn descriptive_variant(&self) -> &str {
2435         match *self {
2436             ForeignItemKind::Fn(..) => "foreign function",
2437             ForeignItemKind::Static(..) => "foreign static item",
2438             ForeignItemKind::Ty => "foreign type",
2439             ForeignItemKind::Macro(..) => "macro in foreign module",
2440         }
2441     }
2442 }