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