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