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