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