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