]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/ast.rs
Overhaul `MacArgs::Eq`.
[rust.git] / compiler / rustc_ast / src / ast.rs
1 //! The Rust abstract syntax tree module.
2 //!
3 //! This module contains common structures forming the language AST.
4 //! Two main entities in the module are [`Item`] (which represents an AST element with
5 //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
6 //! information specific to the type of the item).
7 //!
8 //! Other module items worth mentioning:
9 //! - [`Ty`] and [`TyKind`]: A parsed Rust type.
10 //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
11 //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
12 //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
13 //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
14 //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
15 //! - [`EnumDef`] and [`Variant`]: Enum declaration.
16 //! - [`Lit`] and [`LitKind`]: Literal expressions.
17 //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation.
18 //! - [`Attribute`]: Metadata associated with item.
19 //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
20
21 pub use crate::util::parser::ExprPrecedence;
22 pub use GenericArgs::*;
23 pub use UnsafeSource::*;
24
25 use crate::ptr::P;
26 use crate::token::{self, CommentKind, Delimiter, Token, TokenKind};
27 use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream, TokenTree};
28
29 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
30 use rustc_data_structures::stack::ensure_sufficient_stack;
31 use rustc_data_structures::sync::Lrc;
32 use rustc_data_structures::thin_vec::ThinVec;
33 use rustc_macros::HashStable_Generic;
34 use rustc_serialize::{self, Decoder, Encoder};
35 use rustc_span::source_map::{respan, Spanned};
36 use rustc_span::symbol::{kw, sym, Ident, Symbol};
37 use rustc_span::{Span, DUMMY_SP};
38
39 use std::cmp::Ordering;
40 use std::convert::TryFrom;
41 use std::fmt;
42 use std::mem;
43
44 #[cfg(test)]
45 mod tests;
46
47 /// A "Label" is an identifier of some point in sources,
48 /// e.g. in the following code:
49 ///
50 /// ```rust
51 /// 'outer: loop {
52 ///     break 'outer;
53 /// }
54 /// ```
55 ///
56 /// `'outer` is a label.
57 #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)]
58 pub struct Label {
59     pub ident: Ident,
60 }
61
62 impl fmt::Debug for Label {
63     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64         write!(f, "label({:?})", self.ident)
65     }
66 }
67
68 /// A "Lifetime" is an annotation of the scope in which variable
69 /// can be used, e.g. `'a` in `&'a i32`.
70 #[derive(Clone, Encodable, Decodable, Copy)]
71 pub struct Lifetime {
72     pub id: NodeId,
73     pub ident: Ident,
74 }
75
76 impl fmt::Debug for Lifetime {
77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         write!(f, "lifetime({}: {})", self.id, self)
79     }
80 }
81
82 impl fmt::Display for Lifetime {
83     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84         write!(f, "{}", self.ident.name)
85     }
86 }
87
88 /// A "Path" is essentially Rust's notion of a name.
89 ///
90 /// It's represented as a sequence of identifiers,
91 /// along with a bunch of supporting information.
92 ///
93 /// E.g., `std::cmp::PartialEq`.
94 #[derive(Clone, Encodable, Decodable, Debug)]
95 pub struct Path {
96     pub span: Span,
97     /// The segments in the path: the things separated by `::`.
98     /// Global paths begin with `kw::PathRoot`.
99     pub segments: Vec<PathSegment>,
100     pub tokens: Option<LazyTokenStream>,
101 }
102
103 impl PartialEq<Symbol> for Path {
104     #[inline]
105     fn eq(&self, symbol: &Symbol) -> bool {
106         self.segments.len() == 1 && { self.segments[0].ident.name == *symbol }
107     }
108 }
109
110 impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path {
111     fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
112         self.segments.len().hash_stable(hcx, hasher);
113         for segment in &self.segments {
114             segment.ident.hash_stable(hcx, hasher);
115         }
116     }
117 }
118
119 impl Path {
120     // Convert a span and an identifier to the corresponding
121     // one-segment path.
122     pub fn from_ident(ident: Ident) -> Path {
123         Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None }
124     }
125
126     pub fn is_global(&self) -> bool {
127         !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
128     }
129 }
130
131 /// A segment of a path: an identifier, an optional lifetime, and a set of types.
132 ///
133 /// E.g., `std`, `String` or `Box<T>`.
134 #[derive(Clone, Encodable, Decodable, Debug)]
135 pub struct PathSegment {
136     /// The identifier portion of this path segment.
137     pub ident: Ident,
138
139     pub id: NodeId,
140
141     /// Type/lifetime parameters attached to this path. They come in
142     /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
143     /// `None` means that no parameter list is supplied (`Path`),
144     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
145     /// but it can be empty (`Path<>`).
146     /// `P` is used as a size optimization for the common case with no parameters.
147     pub args: Option<P<GenericArgs>>,
148 }
149
150 impl PathSegment {
151     pub fn from_ident(ident: Ident) -> Self {
152         PathSegment { ident, id: DUMMY_NODE_ID, args: None }
153     }
154
155     pub fn path_root(span: Span) -> Self {
156         PathSegment::from_ident(Ident::new(kw::PathRoot, span))
157     }
158
159     pub fn span(&self) -> Span {
160         match &self.args {
161             Some(args) => self.ident.span.to(args.span()),
162             None => self.ident.span,
163         }
164     }
165 }
166
167 /// The arguments of a path segment.
168 ///
169 /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
170 #[derive(Clone, Encodable, Decodable, Debug)]
171 pub enum GenericArgs {
172     /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
173     AngleBracketed(AngleBracketedArgs),
174     /// The `(A, B)` and `C` in `Foo(A, B) -> C`.
175     Parenthesized(ParenthesizedArgs),
176 }
177
178 impl GenericArgs {
179     pub fn is_angle_bracketed(&self) -> bool {
180         matches!(self, AngleBracketed(..))
181     }
182
183     pub fn span(&self) -> Span {
184         match *self {
185             AngleBracketed(ref data) => data.span,
186             Parenthesized(ref data) => data.span,
187         }
188     }
189 }
190
191 /// Concrete argument in the sequence of generic args.
192 #[derive(Clone, Encodable, Decodable, Debug)]
193 pub enum GenericArg {
194     /// `'a` in `Foo<'a>`
195     Lifetime(Lifetime),
196     /// `Bar` in `Foo<Bar>`
197     Type(P<Ty>),
198     /// `1` in `Foo<1>`
199     Const(AnonConst),
200 }
201
202 impl GenericArg {
203     pub fn span(&self) -> Span {
204         match self {
205             GenericArg::Lifetime(lt) => lt.ident.span,
206             GenericArg::Type(ty) => ty.span,
207             GenericArg::Const(ct) => ct.value.span,
208         }
209     }
210 }
211
212 /// A path like `Foo<'a, T>`.
213 #[derive(Clone, Encodable, Decodable, Debug, Default)]
214 pub struct AngleBracketedArgs {
215     /// The overall span.
216     pub span: Span,
217     /// The comma separated parts in the `<...>`.
218     pub args: Vec<AngleBracketedArg>,
219 }
220
221 /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`,
222 /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`.
223 #[derive(Clone, Encodable, Decodable, Debug)]
224 pub enum AngleBracketedArg {
225     /// Argument for a generic parameter.
226     Arg(GenericArg),
227     /// Constraint for an associated item.
228     Constraint(AssocConstraint),
229 }
230
231 impl AngleBracketedArg {
232     pub fn span(&self) -> Span {
233         match self {
234             AngleBracketedArg::Arg(arg) => arg.span(),
235             AngleBracketedArg::Constraint(constraint) => constraint.span,
236         }
237     }
238 }
239
240 impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
241     fn into(self) -> Option<P<GenericArgs>> {
242         Some(P(GenericArgs::AngleBracketed(self)))
243     }
244 }
245
246 impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
247     fn into(self) -> Option<P<GenericArgs>> {
248         Some(P(GenericArgs::Parenthesized(self)))
249     }
250 }
251
252 /// A path like `Foo(A, B) -> C`.
253 #[derive(Clone, Encodable, Decodable, Debug)]
254 pub struct ParenthesizedArgs {
255     /// ```text
256     /// Foo(A, B) -> C
257     /// ^^^^^^^^^^^^^^
258     /// ```
259     pub span: Span,
260
261     /// `(A, B)`
262     pub inputs: Vec<P<Ty>>,
263
264     /// ```text
265     /// Foo(A, B) -> C
266     ///    ^^^^^^
267     /// ```
268     pub inputs_span: Span,
269
270     /// `C`
271     pub output: FnRetTy,
272 }
273
274 impl ParenthesizedArgs {
275     pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
276         let args = self
277             .inputs
278             .iter()
279             .cloned()
280             .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input)))
281             .collect();
282         AngleBracketedArgs { span: self.inputs_span, args }
283     }
284 }
285
286 pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};
287
288 /// A modifier on a bound, e.g., `?Trait` or `~const Trait`.
289 ///
290 /// Negative bounds should also be handled here.
291 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
292 pub enum TraitBoundModifier {
293     /// No modifiers
294     None,
295
296     /// `?Trait`
297     Maybe,
298
299     /// `~const Trait`
300     MaybeConst,
301
302     /// `~const ?Trait`
303     //
304     // This parses but will be rejected during AST validation.
305     MaybeConstMaybe,
306 }
307
308 /// The AST represents all type param bounds as types.
309 /// `typeck::collect::compute_bounds` matches these against
310 /// the "special" built-in traits (see `middle::lang_items`) and
311 /// detects `Copy`, `Send` and `Sync`.
312 #[derive(Clone, Encodable, Decodable, Debug)]
313 pub enum GenericBound {
314     Trait(PolyTraitRef, TraitBoundModifier),
315     Outlives(Lifetime),
316 }
317
318 impl GenericBound {
319     pub fn span(&self) -> Span {
320         match self {
321             GenericBound::Trait(ref t, ..) => t.span,
322             GenericBound::Outlives(ref l) => l.ident.span,
323         }
324     }
325 }
326
327 pub type GenericBounds = Vec<GenericBound>;
328
329 /// Specifies the enforced ordering for generic parameters. In the future,
330 /// if we wanted to relax this order, we could override `PartialEq` and
331 /// `PartialOrd`, to allow the kinds to be unordered.
332 #[derive(Hash, Clone, Copy)]
333 pub enum ParamKindOrd {
334     Lifetime,
335     Type,
336     Const,
337     // `Infer` is not actually constructed directly from the AST, but is implicitly constructed
338     // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last.
339     Infer,
340 }
341
342 impl Ord for ParamKindOrd {
343     fn cmp(&self, other: &Self) -> Ordering {
344         use ParamKindOrd::*;
345         let to_int = |v| match v {
346             Lifetime => 0,
347             Infer | Type | Const => 1,
348         };
349
350         to_int(*self).cmp(&to_int(*other))
351     }
352 }
353 impl PartialOrd for ParamKindOrd {
354     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
355         Some(self.cmp(other))
356     }
357 }
358 impl PartialEq for ParamKindOrd {
359     fn eq(&self, other: &Self) -> bool {
360         self.cmp(other) == Ordering::Equal
361     }
362 }
363 impl Eq for ParamKindOrd {}
364
365 impl fmt::Display for ParamKindOrd {
366     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367         match self {
368             ParamKindOrd::Lifetime => "lifetime".fmt(f),
369             ParamKindOrd::Type => "type".fmt(f),
370             ParamKindOrd::Const { .. } => "const".fmt(f),
371             ParamKindOrd::Infer => "infer".fmt(f),
372         }
373     }
374 }
375
376 #[derive(Clone, Encodable, Decodable, Debug)]
377 pub enum GenericParamKind {
378     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
379     Lifetime,
380     Type {
381         default: Option<P<Ty>>,
382     },
383     Const {
384         ty: P<Ty>,
385         /// Span of the `const` keyword.
386         kw_span: Span,
387         /// Optional default value for the const generic param
388         default: Option<AnonConst>,
389     },
390 }
391
392 #[derive(Clone, Encodable, Decodable, Debug)]
393 pub struct GenericParam {
394     pub id: NodeId,
395     pub ident: Ident,
396     pub attrs: AttrVec,
397     pub bounds: GenericBounds,
398     pub is_placeholder: bool,
399     pub kind: GenericParamKind,
400 }
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)]
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         /// The "value".
1540         MacArgsEq,
1541     ),
1542 }
1543
1544 // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion
1545 // is completed, all cases end up either as a literal, which is the form used
1546 // after lowering to HIR, or as an error.
1547 #[derive(Clone, Encodable, Decodable, Debug)]
1548 pub enum MacArgsEq {
1549     Ast(P<Expr>),
1550     Hir(Lit),
1551 }
1552
1553 impl MacArgs {
1554     pub fn delim(&self) -> Option<Delimiter> {
1555         match self {
1556             MacArgs::Delimited(_, delim, _) => Some(delim.to_token()),
1557             MacArgs::Empty | MacArgs::Eq(..) => None,
1558         }
1559     }
1560
1561     pub fn span(&self) -> Option<Span> {
1562         match self {
1563             MacArgs::Empty => None,
1564             MacArgs::Delimited(dspan, ..) => Some(dspan.entire()),
1565             MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)),
1566             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1567                 unreachable!("in literal form when getting span: {:?}", lit);
1568             }
1569         }
1570     }
1571
1572     /// Tokens inside the delimiters or after `=`.
1573     /// Proc macros see these tokens, for example.
1574     pub fn inner_tokens(&self) -> TokenStream {
1575         match self {
1576             MacArgs::Empty => TokenStream::default(),
1577             MacArgs::Delimited(.., tokens) => tokens.clone(),
1578             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => {
1579                 // Currently only literals are allowed here. If more complex expression kinds are
1580                 // allowed in the future, then `nt_to_tokenstream` should be used to extract the
1581                 // token stream. This will require some cleverness, perhaps with a function
1582                 // pointer, because `nt_to_tokenstream` is not directly usable from this crate.
1583                 // It will also require changing the `parse_expr` call in `parse_mac_args_common`
1584                 // to `parse_expr_force_collect`.
1585                 if let ExprKind::Lit(lit) = &expr.kind {
1586                     let token = Token::new(TokenKind::Literal(lit.token), lit.span);
1587                     TokenTree::Token(token).into()
1588                 } else {
1589                     unreachable!("couldn't extract literal when getting inner tokens: {:?}", expr)
1590                 }
1591             }
1592             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => {
1593                 unreachable!("in literal form when getting inner tokens: {:?}", lit)
1594             }
1595         }
1596     }
1597
1598     /// Whether a macro with these arguments needs a semicolon
1599     /// when used as a standalone item or statement.
1600     pub fn need_semicolon(&self) -> bool {
1601         !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _))
1602     }
1603 }
1604
1605 impl<CTX> HashStable<CTX> for MacArgs
1606 where
1607     CTX: crate::HashStableContext,
1608 {
1609     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1610         mem::discriminant(self).hash_stable(ctx, hasher);
1611         match self {
1612             MacArgs::Empty => {}
1613             MacArgs::Delimited(dspan, delim, tokens) => {
1614                 dspan.hash_stable(ctx, hasher);
1615                 delim.hash_stable(ctx, hasher);
1616                 tokens.hash_stable(ctx, hasher);
1617             }
1618             MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => {
1619                 unreachable!("hash_stable {:?}", expr);
1620             }
1621             MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => {
1622                 eq_span.hash_stable(ctx, hasher);
1623                 lit.hash_stable(ctx, hasher);
1624             }
1625         }
1626     }
1627 }
1628
1629 #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)]
1630 pub enum MacDelimiter {
1631     Parenthesis,
1632     Bracket,
1633     Brace,
1634 }
1635
1636 impl MacDelimiter {
1637     pub fn to_token(self) -> Delimiter {
1638         match self {
1639             MacDelimiter::Parenthesis => Delimiter::Parenthesis,
1640             MacDelimiter::Bracket => Delimiter::Bracket,
1641             MacDelimiter::Brace => Delimiter::Brace,
1642         }
1643     }
1644
1645     pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> {
1646         match delim {
1647             Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis),
1648             Delimiter::Bracket => Some(MacDelimiter::Bracket),
1649             Delimiter::Brace => Some(MacDelimiter::Brace),
1650             Delimiter::Invisible => None,
1651         }
1652     }
1653 }
1654
1655 /// Represents a macro definition.
1656 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1657 pub struct MacroDef {
1658     pub body: P<MacArgs>,
1659     /// `true` if macro was defined with `macro_rules`.
1660     pub macro_rules: bool,
1661 }
1662
1663 #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
1664 #[derive(HashStable_Generic)]
1665 pub enum StrStyle {
1666     /// A regular string, like `"foo"`.
1667     Cooked,
1668     /// A raw string, like `r##"foo"##`.
1669     ///
1670     /// The value is the number of `#` symbols used.
1671     Raw(u8),
1672 }
1673
1674 /// An AST literal.
1675 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
1676 pub struct Lit {
1677     /// The original literal token as written in source code.
1678     pub token: token::Lit,
1679     /// The "semantic" representation of the literal lowered from the original tokens.
1680     /// Strings are unescaped, hexadecimal forms are eliminated, etc.
1681     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1682     pub kind: LitKind,
1683     pub span: Span,
1684 }
1685
1686 /// Same as `Lit`, but restricted to string literals.
1687 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
1688 pub struct StrLit {
1689     /// The original literal token as written in source code.
1690     pub style: StrStyle,
1691     pub symbol: Symbol,
1692     pub suffix: Option<Symbol>,
1693     pub span: Span,
1694     /// The unescaped "semantic" representation of the literal lowered from the original token.
1695     /// FIXME: Remove this and only create the semantic representation during lowering to HIR.
1696     pub symbol_unescaped: Symbol,
1697 }
1698
1699 impl StrLit {
1700     pub fn as_lit(&self) -> Lit {
1701         let token_kind = match self.style {
1702             StrStyle::Cooked => token::Str,
1703             StrStyle::Raw(n) => token::StrRaw(n),
1704         };
1705         Lit {
1706             token: token::Lit::new(token_kind, self.symbol, self.suffix),
1707             span: self.span,
1708             kind: LitKind::Str(self.symbol_unescaped, self.style),
1709         }
1710     }
1711 }
1712
1713 /// Type of the integer literal based on provided suffix.
1714 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1715 #[derive(HashStable_Generic)]
1716 pub enum LitIntType {
1717     /// e.g. `42_i32`.
1718     Signed(IntTy),
1719     /// e.g. `42_u32`.
1720     Unsigned(UintTy),
1721     /// e.g. `42`.
1722     Unsuffixed,
1723 }
1724
1725 /// Type of the float literal based on provided suffix.
1726 #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1727 #[derive(HashStable_Generic)]
1728 pub enum LitFloatType {
1729     /// A float literal with a suffix (`1f32` or `1E10f32`).
1730     Suffixed(FloatTy),
1731     /// A float literal without a suffix (`1.0 or 1.0E10`).
1732     Unsuffixed,
1733 }
1734
1735 /// Literal kind.
1736 ///
1737 /// E.g., `"foo"`, `42`, `12.34`, or `bool`.
1738 #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)]
1739 pub enum LitKind {
1740     /// A string literal (`"foo"`).
1741     Str(Symbol, StrStyle),
1742     /// A byte string (`b"foo"`).
1743     ByteStr(Lrc<[u8]>),
1744     /// A byte char (`b'f'`).
1745     Byte(u8),
1746     /// A character literal (`'a'`).
1747     Char(char),
1748     /// An integer literal (`1`).
1749     Int(u128, LitIntType),
1750     /// A float literal (`1f64` or `1E10f64`).
1751     Float(Symbol, LitFloatType),
1752     /// A boolean literal.
1753     Bool(bool),
1754     /// Placeholder for a literal that wasn't well-formed in some way.
1755     Err(Symbol),
1756 }
1757
1758 impl LitKind {
1759     /// Returns `true` if this literal is a string.
1760     pub fn is_str(&self) -> bool {
1761         matches!(self, LitKind::Str(..))
1762     }
1763
1764     /// Returns `true` if this literal is byte literal string.
1765     pub fn is_bytestr(&self) -> bool {
1766         matches!(self, LitKind::ByteStr(_))
1767     }
1768
1769     /// Returns `true` if this is a numeric literal.
1770     pub fn is_numeric(&self) -> bool {
1771         matches!(self, LitKind::Int(..) | LitKind::Float(..))
1772     }
1773
1774     /// Returns `true` if this literal has no suffix.
1775     /// Note: this will return true for literals with prefixes such as raw strings and byte strings.
1776     pub fn is_unsuffixed(&self) -> bool {
1777         !self.is_suffixed()
1778     }
1779
1780     /// Returns `true` if this literal has a suffix.
1781     pub fn is_suffixed(&self) -> bool {
1782         match *self {
1783             // suffixed variants
1784             LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..))
1785             | LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
1786             // unsuffixed variants
1787             LitKind::Str(..)
1788             | LitKind::ByteStr(..)
1789             | LitKind::Byte(..)
1790             | LitKind::Char(..)
1791             | LitKind::Int(_, LitIntType::Unsuffixed)
1792             | LitKind::Float(_, LitFloatType::Unsuffixed)
1793             | LitKind::Bool(..)
1794             | LitKind::Err(..) => false,
1795         }
1796     }
1797 }
1798
1799 // N.B., If you change this, you'll probably want to change the corresponding
1800 // type structure in `middle/ty.rs` as well.
1801 #[derive(Clone, Encodable, Decodable, Debug)]
1802 pub struct MutTy {
1803     pub ty: P<Ty>,
1804     pub mutbl: Mutability,
1805 }
1806
1807 /// Represents a function's signature in a trait declaration,
1808 /// trait implementation, or free function.
1809 #[derive(Clone, Encodable, Decodable, Debug)]
1810 pub struct FnSig {
1811     pub header: FnHeader,
1812     pub decl: P<FnDecl>,
1813     pub span: Span,
1814 }
1815
1816 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1817 #[derive(Encodable, Decodable, HashStable_Generic)]
1818 pub enum FloatTy {
1819     F32,
1820     F64,
1821 }
1822
1823 impl FloatTy {
1824     pub fn name_str(self) -> &'static str {
1825         match self {
1826             FloatTy::F32 => "f32",
1827             FloatTy::F64 => "f64",
1828         }
1829     }
1830
1831     pub fn name(self) -> Symbol {
1832         match self {
1833             FloatTy::F32 => sym::f32,
1834             FloatTy::F64 => sym::f64,
1835         }
1836     }
1837 }
1838
1839 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1840 #[derive(Encodable, Decodable, HashStable_Generic)]
1841 pub enum IntTy {
1842     Isize,
1843     I8,
1844     I16,
1845     I32,
1846     I64,
1847     I128,
1848 }
1849
1850 impl IntTy {
1851     pub fn name_str(&self) -> &'static str {
1852         match *self {
1853             IntTy::Isize => "isize",
1854             IntTy::I8 => "i8",
1855             IntTy::I16 => "i16",
1856             IntTy::I32 => "i32",
1857             IntTy::I64 => "i64",
1858             IntTy::I128 => "i128",
1859         }
1860     }
1861
1862     pub fn name(&self) -> Symbol {
1863         match *self {
1864             IntTy::Isize => sym::isize,
1865             IntTy::I8 => sym::i8,
1866             IntTy::I16 => sym::i16,
1867             IntTy::I32 => sym::i32,
1868             IntTy::I64 => sym::i64,
1869             IntTy::I128 => sym::i128,
1870         }
1871     }
1872 }
1873
1874 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)]
1875 #[derive(Encodable, Decodable, HashStable_Generic)]
1876 pub enum UintTy {
1877     Usize,
1878     U8,
1879     U16,
1880     U32,
1881     U64,
1882     U128,
1883 }
1884
1885 impl UintTy {
1886     pub fn name_str(&self) -> &'static str {
1887         match *self {
1888             UintTy::Usize => "usize",
1889             UintTy::U8 => "u8",
1890             UintTy::U16 => "u16",
1891             UintTy::U32 => "u32",
1892             UintTy::U64 => "u64",
1893             UintTy::U128 => "u128",
1894         }
1895     }
1896
1897     pub fn name(&self) -> Symbol {
1898         match *self {
1899             UintTy::Usize => sym::usize,
1900             UintTy::U8 => sym::u8,
1901             UintTy::U16 => sym::u16,
1902             UintTy::U32 => sym::u32,
1903             UintTy::U64 => sym::u64,
1904             UintTy::U128 => sym::u128,
1905         }
1906     }
1907 }
1908
1909 /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
1910 /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
1911 #[derive(Clone, Encodable, Decodable, Debug)]
1912 pub struct AssocConstraint {
1913     pub id: NodeId,
1914     pub ident: Ident,
1915     pub gen_args: Option<GenericArgs>,
1916     pub kind: AssocConstraintKind,
1917     pub span: Span,
1918 }
1919
1920 /// The kinds of an `AssocConstraint`.
1921 #[derive(Clone, Encodable, Decodable, Debug)]
1922 pub enum Term {
1923     Ty(P<Ty>),
1924     Const(AnonConst),
1925 }
1926
1927 impl From<P<Ty>> for Term {
1928     fn from(v: P<Ty>) -> Self {
1929         Term::Ty(v)
1930     }
1931 }
1932
1933 impl From<AnonConst> for Term {
1934     fn from(v: AnonConst) -> Self {
1935         Term::Const(v)
1936     }
1937 }
1938
1939 /// The kinds of an `AssocConstraint`.
1940 #[derive(Clone, Encodable, Decodable, Debug)]
1941 pub enum AssocConstraintKind {
1942     /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type.
1943     Equality { term: Term },
1944     /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
1945     Bound { bounds: GenericBounds },
1946 }
1947
1948 #[derive(Encodable, Decodable, Debug)]
1949 pub struct Ty {
1950     pub id: NodeId,
1951     pub kind: TyKind,
1952     pub span: Span,
1953     pub tokens: Option<LazyTokenStream>,
1954 }
1955
1956 impl Clone for Ty {
1957     fn clone(&self) -> Self {
1958         ensure_sufficient_stack(|| Self {
1959             id: self.id,
1960             kind: self.kind.clone(),
1961             span: self.span,
1962             tokens: self.tokens.clone(),
1963         })
1964     }
1965 }
1966
1967 impl Ty {
1968     pub fn peel_refs(&self) -> &Self {
1969         let mut final_ty = self;
1970         while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind {
1971             final_ty = &ty;
1972         }
1973         final_ty
1974     }
1975 }
1976
1977 #[derive(Clone, Encodable, Decodable, Debug)]
1978 pub struct BareFnTy {
1979     pub unsafety: Unsafe,
1980     pub ext: Extern,
1981     pub generic_params: Vec<GenericParam>,
1982     pub decl: P<FnDecl>,
1983 }
1984
1985 /// The various kinds of type recognized by the compiler.
1986 #[derive(Clone, Encodable, Decodable, Debug)]
1987 pub enum TyKind {
1988     /// A variable-length slice (`[T]`).
1989     Slice(P<Ty>),
1990     /// A fixed length array (`[T; n]`).
1991     Array(P<Ty>, AnonConst),
1992     /// A raw pointer (`*const T` or `*mut T`).
1993     Ptr(MutTy),
1994     /// A reference (`&'a T` or `&'a mut T`).
1995     Rptr(Option<Lifetime>, MutTy),
1996     /// A bare function (e.g., `fn(usize) -> bool`).
1997     BareFn(P<BareFnTy>),
1998     /// The never type (`!`).
1999     Never,
2000     /// A tuple (`(A, B, C, D,...)`).
2001     Tup(Vec<P<Ty>>),
2002     /// A path (`module::module::...::Type`), optionally
2003     /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
2004     ///
2005     /// Type parameters are stored in the `Path` itself.
2006     Path(Option<QSelf>, Path),
2007     /// A trait object type `Bound1 + Bound2 + Bound3`
2008     /// where `Bound` is a trait or a lifetime.
2009     TraitObject(GenericBounds, TraitObjectSyntax),
2010     /// An `impl Bound1 + Bound2 + Bound3` type
2011     /// where `Bound` is a trait or a lifetime.
2012     ///
2013     /// The `NodeId` exists to prevent lowering from having to
2014     /// generate `NodeId`s on the fly, which would complicate
2015     /// the generation of opaque `type Foo = impl Trait` items significantly.
2016     ImplTrait(NodeId, GenericBounds),
2017     /// No-op; kept solely so that we can pretty-print faithfully.
2018     Paren(P<Ty>),
2019     /// Unused for now.
2020     Typeof(AnonConst),
2021     /// This means the type should be inferred instead of it having been
2022     /// specified. This can appear anywhere in a type.
2023     Infer,
2024     /// Inferred type of a `self` or `&self` argument in a method.
2025     ImplicitSelf,
2026     /// A macro in the type position.
2027     MacCall(MacCall),
2028     /// Placeholder for a kind that has failed to be defined.
2029     Err,
2030     /// Placeholder for a `va_list`.
2031     CVarArgs,
2032 }
2033
2034 impl TyKind {
2035     pub fn is_implicit_self(&self) -> bool {
2036         matches!(self, TyKind::ImplicitSelf)
2037     }
2038
2039     pub fn is_unit(&self) -> bool {
2040         matches!(self, TyKind::Tup(tys) if tys.is_empty())
2041     }
2042 }
2043
2044 /// Syntax used to declare a trait object.
2045 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2046 pub enum TraitObjectSyntax {
2047     Dyn,
2048     None,
2049 }
2050
2051 /// Inline assembly operand explicit register or register class.
2052 ///
2053 /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`.
2054 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2055 pub enum InlineAsmRegOrRegClass {
2056     Reg(Symbol),
2057     RegClass(Symbol),
2058 }
2059
2060 bitflags::bitflags! {
2061     #[derive(Encodable, Decodable, HashStable_Generic)]
2062     pub struct InlineAsmOptions: u16 {
2063         const PURE = 1 << 0;
2064         const NOMEM = 1 << 1;
2065         const READONLY = 1 << 2;
2066         const PRESERVES_FLAGS = 1 << 3;
2067         const NORETURN = 1 << 4;
2068         const NOSTACK = 1 << 5;
2069         const ATT_SYNTAX = 1 << 6;
2070         const RAW = 1 << 7;
2071         const MAY_UNWIND = 1 << 8;
2072     }
2073 }
2074
2075 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)]
2076 pub enum InlineAsmTemplatePiece {
2077     String(String),
2078     Placeholder { operand_idx: usize, modifier: Option<char>, span: Span },
2079 }
2080
2081 impl fmt::Display for InlineAsmTemplatePiece {
2082     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2083         match self {
2084             Self::String(s) => {
2085                 for c in s.chars() {
2086                     match c {
2087                         '{' => f.write_str("{{")?,
2088                         '}' => f.write_str("}}")?,
2089                         _ => c.fmt(f)?,
2090                     }
2091                 }
2092                 Ok(())
2093             }
2094             Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => {
2095                 write!(f, "{{{}:{}}}", operand_idx, modifier)
2096             }
2097             Self::Placeholder { operand_idx, modifier: None, .. } => {
2098                 write!(f, "{{{}}}", operand_idx)
2099             }
2100         }
2101     }
2102 }
2103
2104 impl InlineAsmTemplatePiece {
2105     /// Rebuilds the asm template string from its pieces.
2106     pub fn to_string(s: &[Self]) -> String {
2107         use fmt::Write;
2108         let mut out = String::new();
2109         for p in s.iter() {
2110             let _ = write!(out, "{}", p);
2111         }
2112         out
2113     }
2114 }
2115
2116 /// Inline assembly symbol operands get their own AST node that is somewhat
2117 /// similar to `AnonConst`.
2118 ///
2119 /// The main difference is that we specifically don't assign it `DefId` in
2120 /// `DefCollector`. Instead this is deferred until AST lowering where we
2121 /// lower it to an `AnonConst` (for functions) or a `Path` (for statics)
2122 /// depending on what the path resolves to.
2123 #[derive(Clone, Encodable, Decodable, Debug)]
2124 pub struct InlineAsmSym {
2125     pub id: NodeId,
2126     pub qself: Option<QSelf>,
2127     pub path: Path,
2128 }
2129
2130 /// Inline assembly operand.
2131 ///
2132 /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`.
2133 #[derive(Clone, Encodable, Decodable, Debug)]
2134 pub enum InlineAsmOperand {
2135     In {
2136         reg: InlineAsmRegOrRegClass,
2137         expr: P<Expr>,
2138     },
2139     Out {
2140         reg: InlineAsmRegOrRegClass,
2141         late: bool,
2142         expr: Option<P<Expr>>,
2143     },
2144     InOut {
2145         reg: InlineAsmRegOrRegClass,
2146         late: bool,
2147         expr: P<Expr>,
2148     },
2149     SplitInOut {
2150         reg: InlineAsmRegOrRegClass,
2151         late: bool,
2152         in_expr: P<Expr>,
2153         out_expr: Option<P<Expr>>,
2154     },
2155     Const {
2156         anon_const: AnonConst,
2157     },
2158     Sym {
2159         sym: InlineAsmSym,
2160     },
2161 }
2162
2163 /// Inline assembly.
2164 ///
2165 /// E.g., `asm!("NOP");`.
2166 #[derive(Clone, Encodable, Decodable, Debug)]
2167 pub struct InlineAsm {
2168     pub template: Vec<InlineAsmTemplatePiece>,
2169     pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>,
2170     pub operands: Vec<(InlineAsmOperand, Span)>,
2171     pub clobber_abis: Vec<(Symbol, Span)>,
2172     pub options: InlineAsmOptions,
2173     pub line_spans: Vec<Span>,
2174 }
2175
2176 /// A parameter in a function header.
2177 ///
2178 /// E.g., `bar: usize` as in `fn foo(bar: usize)`.
2179 #[derive(Clone, Encodable, Decodable, Debug)]
2180 pub struct Param {
2181     pub attrs: AttrVec,
2182     pub ty: P<Ty>,
2183     pub pat: P<Pat>,
2184     pub id: NodeId,
2185     pub span: Span,
2186     pub is_placeholder: bool,
2187 }
2188
2189 /// Alternative representation for `Arg`s describing `self` parameter of methods.
2190 ///
2191 /// E.g., `&mut self` as in `fn foo(&mut self)`.
2192 #[derive(Clone, Encodable, Decodable, Debug)]
2193 pub enum SelfKind {
2194     /// `self`, `mut self`
2195     Value(Mutability),
2196     /// `&'lt self`, `&'lt mut self`
2197     Region(Option<Lifetime>, Mutability),
2198     /// `self: TYPE`, `mut self: TYPE`
2199     Explicit(P<Ty>, Mutability),
2200 }
2201
2202 pub type ExplicitSelf = Spanned<SelfKind>;
2203
2204 impl Param {
2205     /// Attempts to cast parameter to `ExplicitSelf`.
2206     pub fn to_self(&self) -> Option<ExplicitSelf> {
2207         if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
2208             if ident.name == kw::SelfLower {
2209                 return match self.ty.kind {
2210                     TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
2211                     TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
2212                         Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
2213                     }
2214                     _ => Some(respan(
2215                         self.pat.span.to(self.ty.span),
2216                         SelfKind::Explicit(self.ty.clone(), mutbl),
2217                     )),
2218                 };
2219             }
2220         }
2221         None
2222     }
2223
2224     /// Returns `true` if parameter is `self`.
2225     pub fn is_self(&self) -> bool {
2226         if let PatKind::Ident(_, ident, _) = self.pat.kind {
2227             ident.name == kw::SelfLower
2228         } else {
2229             false
2230         }
2231     }
2232
2233     /// Builds a `Param` object from `ExplicitSelf`.
2234     pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param {
2235         let span = eself.span.to(eself_ident.span);
2236         let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None });
2237         let param = |mutbl, ty| Param {
2238             attrs,
2239             pat: P(Pat {
2240                 id: DUMMY_NODE_ID,
2241                 kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
2242                 span,
2243                 tokens: None,
2244             }),
2245             span,
2246             ty,
2247             id: DUMMY_NODE_ID,
2248             is_placeholder: false,
2249         };
2250         match eself.node {
2251             SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
2252             SelfKind::Value(mutbl) => param(mutbl, infer_ty),
2253             SelfKind::Region(lt, mutbl) => param(
2254                 Mutability::Not,
2255                 P(Ty {
2256                     id: DUMMY_NODE_ID,
2257                     kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }),
2258                     span,
2259                     tokens: None,
2260                 }),
2261             ),
2262         }
2263     }
2264 }
2265
2266 /// A signature (not the body) of a function declaration.
2267 ///
2268 /// E.g., `fn foo(bar: baz)`.
2269 ///
2270 /// Please note that it's different from `FnHeader` structure
2271 /// which contains metadata about function safety, asyncness, constness and ABI.
2272 #[derive(Clone, Encodable, Decodable, Debug)]
2273 pub struct FnDecl {
2274     pub inputs: Vec<Param>,
2275     pub output: FnRetTy,
2276 }
2277
2278 impl FnDecl {
2279     pub fn has_self(&self) -> bool {
2280         self.inputs.get(0).map_or(false, Param::is_self)
2281     }
2282     pub fn c_variadic(&self) -> bool {
2283         self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs))
2284     }
2285 }
2286
2287 /// Is the trait definition an auto trait?
2288 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2289 pub enum IsAuto {
2290     Yes,
2291     No,
2292 }
2293
2294 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2295 #[derive(HashStable_Generic)]
2296 pub enum Unsafe {
2297     Yes(Span),
2298     No,
2299 }
2300
2301 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2302 pub enum Async {
2303     Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId },
2304     No,
2305 }
2306
2307 impl Async {
2308     pub fn is_async(self) -> bool {
2309         matches!(self, Async::Yes { .. })
2310     }
2311
2312     /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
2313     pub fn opt_return_id(self) -> Option<NodeId> {
2314         match self {
2315             Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id),
2316             Async::No => None,
2317         }
2318     }
2319 }
2320
2321 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
2322 #[derive(HashStable_Generic)]
2323 pub enum Const {
2324     Yes(Span),
2325     No,
2326 }
2327
2328 /// Item defaultness.
2329 /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
2330 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
2331 pub enum Defaultness {
2332     Default(Span),
2333     Final,
2334 }
2335
2336 #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
2337 pub enum ImplPolarity {
2338     /// `impl Trait for Type`
2339     Positive,
2340     /// `impl !Trait for Type`
2341     Negative(Span),
2342 }
2343
2344 impl fmt::Debug for ImplPolarity {
2345     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2346         match *self {
2347             ImplPolarity::Positive => "positive".fmt(f),
2348             ImplPolarity::Negative(_) => "negative".fmt(f),
2349         }
2350     }
2351 }
2352
2353 #[derive(Clone, Encodable, Decodable, Debug)]
2354 pub enum FnRetTy {
2355     /// Returns type is not specified.
2356     ///
2357     /// Functions default to `()` and closures default to inference.
2358     /// Span points to where return type would be inserted.
2359     Default(Span),
2360     /// Everything else.
2361     Ty(P<Ty>),
2362 }
2363
2364 impl FnRetTy {
2365     pub fn span(&self) -> Span {
2366         match *self {
2367             FnRetTy::Default(span) => span,
2368             FnRetTy::Ty(ref ty) => ty.span,
2369         }
2370     }
2371 }
2372
2373 #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)]
2374 pub enum Inline {
2375     Yes,
2376     No,
2377 }
2378
2379 /// Module item kind.
2380 #[derive(Clone, Encodable, Decodable, Debug)]
2381 pub enum ModKind {
2382     /// Module with inlined definition `mod foo { ... }`,
2383     /// or with definition outlined to a separate file `mod foo;` and already loaded from it.
2384     /// The inner span is from the first token past `{` to the last token until `}`,
2385     /// or from the first to the last token in the loaded file.
2386     Loaded(Vec<P<Item>>, Inline, ModSpans),
2387     /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it.
2388     Unloaded,
2389 }
2390
2391 #[derive(Copy, Clone, Encodable, Decodable, Debug)]
2392 pub struct ModSpans {
2393     /// `inner_span` covers the body of the module; for a file module, its the whole file.
2394     /// For an inline module, its the span inside the `{ ... }`, not including the curly braces.
2395     pub inner_span: Span,
2396     pub inject_use_span: Span,
2397 }
2398
2399 impl Default for ModSpans {
2400     fn default() -> ModSpans {
2401         ModSpans { inner_span: Default::default(), inject_use_span: Default::default() }
2402     }
2403 }
2404
2405 /// Foreign module declaration.
2406 ///
2407 /// E.g., `extern { .. }` or `extern "C" { .. }`.
2408 #[derive(Clone, Encodable, Decodable, Debug)]
2409 pub struct ForeignMod {
2410     /// `unsafe` keyword accepted syntactically for macro DSLs, but not
2411     /// semantically by Rust.
2412     pub unsafety: Unsafe,
2413     pub abi: Option<StrLit>,
2414     pub items: Vec<P<ForeignItem>>,
2415 }
2416
2417 #[derive(Clone, Encodable, Decodable, Debug)]
2418 pub struct EnumDef {
2419     pub variants: Vec<Variant>,
2420 }
2421 /// Enum variant.
2422 #[derive(Clone, Encodable, Decodable, Debug)]
2423 pub struct Variant {
2424     /// Attributes of the variant.
2425     pub attrs: AttrVec,
2426     /// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
2427     pub id: NodeId,
2428     /// Span
2429     pub span: Span,
2430     /// The visibility of the variant. Syntactically accepted but not semantically.
2431     pub vis: Visibility,
2432     /// Name of the variant.
2433     pub ident: Ident,
2434
2435     /// Fields and constructor id of the variant.
2436     pub data: VariantData,
2437     /// Explicit discriminant, e.g., `Foo = 1`.
2438     pub disr_expr: Option<AnonConst>,
2439     /// Is a macro placeholder
2440     pub is_placeholder: bool,
2441 }
2442
2443 /// Part of `use` item to the right of its prefix.
2444 #[derive(Clone, Encodable, Decodable, Debug)]
2445 pub enum UseTreeKind {
2446     /// `use prefix` or `use prefix as rename`
2447     ///
2448     /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
2449     /// namespace.
2450     Simple(Option<Ident>, NodeId, NodeId),
2451     /// `use prefix::{...}`
2452     Nested(Vec<(UseTree, NodeId)>),
2453     /// `use prefix::*`
2454     Glob,
2455 }
2456
2457 /// A tree of paths sharing common prefixes.
2458 /// Used in `use` items both at top-level and inside of braces in import groups.
2459 #[derive(Clone, Encodable, Decodable, Debug)]
2460 pub struct UseTree {
2461     pub prefix: Path,
2462     pub kind: UseTreeKind,
2463     pub span: Span,
2464 }
2465
2466 impl UseTree {
2467     pub fn ident(&self) -> Ident {
2468         match self.kind {
2469             UseTreeKind::Simple(Some(rename), ..) => rename,
2470             UseTreeKind::Simple(None, ..) => {
2471                 self.prefix.segments.last().expect("empty prefix in a simple import").ident
2472             }
2473             _ => panic!("`UseTree::ident` can only be used on a simple import"),
2474         }
2475     }
2476 }
2477
2478 /// Distinguishes between `Attribute`s that decorate items and Attributes that
2479 /// are contained as statements within items. These two cases need to be
2480 /// distinguished for pretty-printing.
2481 #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2482 pub enum AttrStyle {
2483     Outer,
2484     Inner,
2485 }
2486
2487 rustc_index::newtype_index! {
2488     pub struct AttrId {
2489         ENCODABLE = custom
2490         DEBUG_FORMAT = "AttrId({})"
2491     }
2492 }
2493
2494 impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
2495     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
2496         s.emit_unit()
2497     }
2498 }
2499
2500 impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
2501     fn decode(_: &mut D) -> AttrId {
2502         crate::attr::mk_attr_id()
2503     }
2504 }
2505
2506 #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2507 pub struct AttrItem {
2508     pub path: Path,
2509     pub args: MacArgs,
2510     pub tokens: Option<LazyTokenStream>,
2511 }
2512
2513 /// A list of attributes.
2514 pub type AttrVec = ThinVec<Attribute>;
2515
2516 /// Metadata associated with an item.
2517 #[derive(Clone, Encodable, Decodable, Debug)]
2518 pub struct Attribute {
2519     pub kind: AttrKind,
2520     pub id: AttrId,
2521     /// Denotes if the attribute decorates the following construct (outer)
2522     /// or the construct this attribute is contained within (inner).
2523     pub style: AttrStyle,
2524     pub span: Span,
2525 }
2526
2527 #[derive(Clone, Encodable, Decodable, Debug)]
2528 pub enum AttrKind {
2529     /// A normal attribute.
2530     Normal(AttrItem, Option<LazyTokenStream>),
2531
2532     /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
2533     /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
2534     /// variant (which is much less compact and thus more expensive).
2535     DocComment(CommentKind, Symbol),
2536 }
2537
2538 /// `TraitRef`s appear in impls.
2539 ///
2540 /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
2541 /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
2542 /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
2543 /// same as the impl's `NodeId`).
2544 #[derive(Clone, Encodable, Decodable, Debug)]
2545 pub struct TraitRef {
2546     pub path: Path,
2547     pub ref_id: NodeId,
2548 }
2549
2550 #[derive(Clone, Encodable, Decodable, Debug)]
2551 pub struct PolyTraitRef {
2552     /// The `'a` in `for<'a> Foo<&'a T>`.
2553     pub bound_generic_params: Vec<GenericParam>,
2554
2555     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
2556     pub trait_ref: TraitRef,
2557
2558     pub span: Span,
2559 }
2560
2561 impl PolyTraitRef {
2562     pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
2563         PolyTraitRef {
2564             bound_generic_params: generic_params,
2565             trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID },
2566             span,
2567         }
2568     }
2569 }
2570
2571 #[derive(Copy, Clone, Encodable, Decodable, Debug, HashStable_Generic)]
2572 pub enum CrateSugar {
2573     /// Source is `pub(crate)`.
2574     PubCrate,
2575
2576     /// Source is (just) `crate`.
2577     JustCrate,
2578 }
2579
2580 #[derive(Clone, Encodable, Decodable, Debug)]
2581 pub struct Visibility {
2582     pub kind: VisibilityKind,
2583     pub span: Span,
2584     pub tokens: Option<LazyTokenStream>,
2585 }
2586
2587 #[derive(Clone, Encodable, Decodable, Debug)]
2588 pub enum VisibilityKind {
2589     Public,
2590     Crate(CrateSugar),
2591     Restricted { path: P<Path>, id: NodeId },
2592     Inherited,
2593 }
2594
2595 impl VisibilityKind {
2596     pub fn is_pub(&self) -> bool {
2597         matches!(self, VisibilityKind::Public)
2598     }
2599 }
2600
2601 /// Field definition in a struct, variant or union.
2602 ///
2603 /// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
2604 #[derive(Clone, Encodable, Decodable, Debug)]
2605 pub struct FieldDef {
2606     pub attrs: AttrVec,
2607     pub id: NodeId,
2608     pub span: Span,
2609     pub vis: Visibility,
2610     pub ident: Option<Ident>,
2611
2612     pub ty: P<Ty>,
2613     pub is_placeholder: bool,
2614 }
2615
2616 /// Fields and constructor ids of enum variants and structs.
2617 #[derive(Clone, Encodable, Decodable, Debug)]
2618 pub enum VariantData {
2619     /// Struct variant.
2620     ///
2621     /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
2622     Struct(Vec<FieldDef>, bool),
2623     /// Tuple variant.
2624     ///
2625     /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
2626     Tuple(Vec<FieldDef>, NodeId),
2627     /// Unit variant.
2628     ///
2629     /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
2630     Unit(NodeId),
2631 }
2632
2633 impl VariantData {
2634     /// Return the fields of this variant.
2635     pub fn fields(&self) -> &[FieldDef] {
2636         match *self {
2637             VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
2638             _ => &[],
2639         }
2640     }
2641
2642     /// Return the `NodeId` of this variant's constructor, if it has one.
2643     pub fn ctor_id(&self) -> Option<NodeId> {
2644         match *self {
2645             VariantData::Struct(..) => None,
2646             VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
2647         }
2648     }
2649 }
2650
2651 /// An item definition.
2652 #[derive(Clone, Encodable, Decodable, Debug)]
2653 pub struct Item<K = ItemKind> {
2654     pub attrs: Vec<Attribute>,
2655     pub id: NodeId,
2656     pub span: Span,
2657     pub vis: Visibility,
2658     /// The name of the item.
2659     /// It might be a dummy name in case of anonymous items.
2660     pub ident: Ident,
2661
2662     pub kind: K,
2663
2664     /// Original tokens this item was parsed from. This isn't necessarily
2665     /// available for all items, although over time more and more items should
2666     /// have this be `Some`. Right now this is primarily used for procedural
2667     /// macros, notably custom attributes.
2668     ///
2669     /// Note that the tokens here do not include the outer attributes, but will
2670     /// include inner attributes.
2671     pub tokens: Option<LazyTokenStream>,
2672 }
2673
2674 impl Item {
2675     /// Return the span that encompasses the attributes.
2676     pub fn span_with_attributes(&self) -> Span {
2677         self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
2678     }
2679 }
2680
2681 impl<K: Into<ItemKind>> Item<K> {
2682     pub fn into_item(self) -> Item {
2683         let Item { attrs, id, span, vis, ident, kind, tokens } = self;
2684         Item { attrs, id, span, vis, ident, kind: kind.into(), tokens }
2685     }
2686 }
2687
2688 /// `extern` qualifier on a function item or function type.
2689 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2690 pub enum Extern {
2691     None,
2692     Implicit,
2693     Explicit(StrLit),
2694 }
2695
2696 impl Extern {
2697     pub fn from_abi(abi: Option<StrLit>) -> Extern {
2698         abi.map_or(Extern::Implicit, Extern::Explicit)
2699     }
2700 }
2701
2702 /// A function header.
2703 ///
2704 /// All the information between the visibility and the name of the function is
2705 /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
2706 #[derive(Clone, Copy, Encodable, Decodable, Debug)]
2707 pub struct FnHeader {
2708     pub unsafety: Unsafe,
2709     pub asyncness: Async,
2710     pub constness: Const,
2711     pub ext: Extern,
2712 }
2713
2714 impl FnHeader {
2715     /// Does this function header have any qualifiers or is it empty?
2716     pub fn has_qualifiers(&self) -> bool {
2717         let Self { unsafety, asyncness, constness, ext } = self;
2718         matches!(unsafety, Unsafe::Yes(_))
2719             || asyncness.is_async()
2720             || matches!(constness, Const::Yes(_))
2721             || !matches!(ext, Extern::None)
2722     }
2723 }
2724
2725 impl Default for FnHeader {
2726     fn default() -> FnHeader {
2727         FnHeader {
2728             unsafety: Unsafe::No,
2729             asyncness: Async::No,
2730             constness: Const::No,
2731             ext: Extern::None,
2732         }
2733     }
2734 }
2735
2736 #[derive(Clone, Encodable, Decodable, Debug)]
2737 pub struct Trait {
2738     pub unsafety: Unsafe,
2739     pub is_auto: IsAuto,
2740     pub generics: Generics,
2741     pub bounds: GenericBounds,
2742     pub items: Vec<P<AssocItem>>,
2743 }
2744
2745 /// The location of a where clause on a `TyAlias` (`Span`) and whether there was
2746 /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there
2747 /// are two locations for where clause on type aliases, but their predicates
2748 /// are concatenated together.
2749 ///
2750 /// Take this example:
2751 /// ```ignore (only-for-syntax-highlight)
2752 /// trait Foo {
2753 ///   type Assoc<'a, 'b> where Self: 'a, Self: 'b;
2754 /// }
2755 /// impl Foo for () {
2756 ///   type Assoc<'a, 'b> where Self: 'a = () where Self: 'b;
2757 ///   //                 ^^^^^^^^^^^^^^ first where clause
2758 ///   //                                     ^^^^^^^^^^^^^^ second where clause
2759 /// }
2760 /// ```
2761 ///
2762 /// If there is no where clause, then this is `false` with `DUMMY_SP`.
2763 #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)]
2764 pub struct TyAliasWhereClause(pub bool, pub Span);
2765
2766 #[derive(Clone, Encodable, Decodable, Debug)]
2767 pub struct TyAlias {
2768     pub defaultness: Defaultness,
2769     pub generics: Generics,
2770     /// The span information for the two where clauses (before equals, after equals)
2771     pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
2772     /// The index in `generics.where_clause.predicates` that would split into
2773     /// predicates from the where clause before the equals and the predicates
2774     /// from the where clause after the equals
2775     pub where_predicates_split: usize,
2776     pub bounds: GenericBounds,
2777     pub ty: Option<P<Ty>>,
2778 }
2779
2780 #[derive(Clone, Encodable, Decodable, Debug)]
2781 pub struct Impl {
2782     pub defaultness: Defaultness,
2783     pub unsafety: Unsafe,
2784     pub generics: Generics,
2785     pub constness: Const,
2786     pub polarity: ImplPolarity,
2787     /// The trait being implemented, if any.
2788     pub of_trait: Option<TraitRef>,
2789     pub self_ty: P<Ty>,
2790     pub items: Vec<P<AssocItem>>,
2791 }
2792
2793 #[derive(Clone, Encodable, Decodable, Debug)]
2794 pub struct Fn {
2795     pub defaultness: Defaultness,
2796     pub generics: Generics,
2797     pub sig: FnSig,
2798     pub body: Option<P<Block>>,
2799 }
2800
2801 #[derive(Clone, Encodable, Decodable, Debug)]
2802 pub enum ItemKind {
2803     /// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
2804     ///
2805     /// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
2806     ExternCrate(Option<Symbol>),
2807     /// A use declaration item (`use`).
2808     ///
2809     /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
2810     Use(UseTree),
2811     /// A static item (`static`).
2812     ///
2813     /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
2814     Static(P<Ty>, Mutability, Option<P<Expr>>),
2815     /// A constant item (`const`).
2816     ///
2817     /// E.g., `const FOO: i32 = 42;`.
2818     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2819     /// A function declaration (`fn`).
2820     ///
2821     /// E.g., `fn foo(bar: usize) -> usize { .. }`.
2822     Fn(Box<Fn>),
2823     /// A module declaration (`mod`).
2824     ///
2825     /// E.g., `mod foo;` or `mod foo { .. }`.
2826     /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
2827     /// semantically by Rust.
2828     Mod(Unsafe, ModKind),
2829     /// An external module (`extern`).
2830     ///
2831     /// E.g., `extern {}` or `extern "C" {}`.
2832     ForeignMod(ForeignMod),
2833     /// Module-level inline assembly (from `global_asm!()`).
2834     GlobalAsm(Box<InlineAsm>),
2835     /// A type alias (`type`).
2836     ///
2837     /// E.g., `type Foo = Bar<u8>;`.
2838     TyAlias(Box<TyAlias>),
2839     /// An enum definition (`enum`).
2840     ///
2841     /// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
2842     Enum(EnumDef, Generics),
2843     /// A struct definition (`struct`).
2844     ///
2845     /// E.g., `struct Foo<A> { x: A }`.
2846     Struct(VariantData, Generics),
2847     /// A union definition (`union`).
2848     ///
2849     /// E.g., `union Foo<A, B> { x: A, y: B }`.
2850     Union(VariantData, Generics),
2851     /// A trait declaration (`trait`).
2852     ///
2853     /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
2854     Trait(Box<Trait>),
2855     /// Trait alias
2856     ///
2857     /// E.g., `trait Foo = Bar + Quux;`.
2858     TraitAlias(Generics, GenericBounds),
2859     /// An implementation.
2860     ///
2861     /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
2862     Impl(Box<Impl>),
2863     /// A macro invocation.
2864     ///
2865     /// E.g., `foo!(..)`.
2866     MacCall(MacCall),
2867
2868     /// A macro definition.
2869     MacroDef(MacroDef),
2870 }
2871
2872 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2873 rustc_data_structures::static_assert_size!(ItemKind, 112);
2874
2875 impl ItemKind {
2876     pub fn article(&self) -> &str {
2877         use ItemKind::*;
2878         match self {
2879             Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..)
2880             | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a",
2881             ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an",
2882         }
2883     }
2884
2885     pub fn descr(&self) -> &str {
2886         match self {
2887             ItemKind::ExternCrate(..) => "extern crate",
2888             ItemKind::Use(..) => "`use` import",
2889             ItemKind::Static(..) => "static item",
2890             ItemKind::Const(..) => "constant item",
2891             ItemKind::Fn(..) => "function",
2892             ItemKind::Mod(..) => "module",
2893             ItemKind::ForeignMod(..) => "extern block",
2894             ItemKind::GlobalAsm(..) => "global asm item",
2895             ItemKind::TyAlias(..) => "type alias",
2896             ItemKind::Enum(..) => "enum",
2897             ItemKind::Struct(..) => "struct",
2898             ItemKind::Union(..) => "union",
2899             ItemKind::Trait(..) => "trait",
2900             ItemKind::TraitAlias(..) => "trait alias",
2901             ItemKind::MacCall(..) => "item macro invocation",
2902             ItemKind::MacroDef(..) => "macro definition",
2903             ItemKind::Impl { .. } => "implementation",
2904         }
2905     }
2906
2907     pub fn generics(&self) -> Option<&Generics> {
2908         match self {
2909             Self::Fn(box Fn { generics, .. })
2910             | Self::TyAlias(box TyAlias { generics, .. })
2911             | Self::Enum(_, generics)
2912             | Self::Struct(_, generics)
2913             | Self::Union(_, generics)
2914             | Self::Trait(box Trait { generics, .. })
2915             | Self::TraitAlias(generics, _)
2916             | Self::Impl(box Impl { generics, .. }) => Some(generics),
2917             _ => None,
2918         }
2919     }
2920 }
2921
2922 /// Represents associated items.
2923 /// These include items in `impl` and `trait` definitions.
2924 pub type AssocItem = Item<AssocItemKind>;
2925
2926 /// Represents associated item kinds.
2927 ///
2928 /// The term "provided" in the variants below refers to the item having a default
2929 /// definition / body. Meanwhile, a "required" item lacks a definition / body.
2930 /// In an implementation, all items must be provided.
2931 /// The `Option`s below denote the bodies, where `Some(_)`
2932 /// means "provided" and conversely `None` means "required".
2933 #[derive(Clone, Encodable, Decodable, Debug)]
2934 pub enum AssocItemKind {
2935     /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`.
2936     /// If `def` is parsed, then the constant is provided, and otherwise required.
2937     Const(Defaultness, P<Ty>, Option<P<Expr>>),
2938     /// An associated function.
2939     Fn(Box<Fn>),
2940     /// An associated type.
2941     TyAlias(Box<TyAlias>),
2942     /// A macro expanding to associated items.
2943     MacCall(MacCall),
2944 }
2945
2946 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2947 rustc_data_structures::static_assert_size!(AssocItemKind, 72);
2948
2949 impl AssocItemKind {
2950     pub fn defaultness(&self) -> Defaultness {
2951         match *self {
2952             Self::Const(defaultness, ..)
2953             | Self::Fn(box Fn { defaultness, .. })
2954             | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
2955             Self::MacCall(..) => Defaultness::Final,
2956         }
2957     }
2958 }
2959
2960 impl From<AssocItemKind> for ItemKind {
2961     fn from(assoc_item_kind: AssocItemKind) -> ItemKind {
2962         match assoc_item_kind {
2963             AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c),
2964             AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
2965             AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
2966             AssocItemKind::MacCall(a) => ItemKind::MacCall(a),
2967         }
2968     }
2969 }
2970
2971 impl TryFrom<ItemKind> for AssocItemKind {
2972     type Error = ItemKind;
2973
2974     fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> {
2975         Ok(match item_kind {
2976             ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c),
2977             ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind),
2978             ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind),
2979             ItemKind::MacCall(a) => AssocItemKind::MacCall(a),
2980             _ => return Err(item_kind),
2981         })
2982     }
2983 }
2984
2985 /// An item in `extern` block.
2986 #[derive(Clone, Encodable, Decodable, Debug)]
2987 pub enum ForeignItemKind {
2988     /// A foreign static item (`static FOO: u8`).
2989     Static(P<Ty>, Mutability, Option<P<Expr>>),
2990     /// An foreign function.
2991     Fn(Box<Fn>),
2992     /// An foreign type.
2993     TyAlias(Box<TyAlias>),
2994     /// A macro expanding to foreign items.
2995     MacCall(MacCall),
2996 }
2997
2998 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2999 rustc_data_structures::static_assert_size!(ForeignItemKind, 72);
3000
3001 impl From<ForeignItemKind> for ItemKind {
3002     fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
3003         match foreign_item_kind {
3004             ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c),
3005             ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
3006             ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
3007             ForeignItemKind::MacCall(a) => ItemKind::MacCall(a),
3008         }
3009     }
3010 }
3011
3012 impl TryFrom<ItemKind> for ForeignItemKind {
3013     type Error = ItemKind;
3014
3015     fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> {
3016         Ok(match item_kind {
3017             ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c),
3018             ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
3019             ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
3020             ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
3021             _ => return Err(item_kind),
3022         })
3023     }
3024 }
3025
3026 pub type ForeignItem = Item<ForeignItemKind>;