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