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