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