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