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