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