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