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