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