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