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