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