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