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