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