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