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