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