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