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