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