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