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