1 //! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate) 2 //! 3 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 //! 7 //! <br> 8 //! 9 //! A wrapper around the procedural macro API of the compiler's [`proc_macro`] 10 //! crate. This library serves two purposes: 11 //! 12 //! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/ 13 //! 14 //! - **Bring proc-macro-like functionality to other contexts like build.rs and 15 //! main.rs.** Types from `proc_macro` are entirely specific to procedural 16 //! macros and cannot ever exist in code outside of a procedural macro. 17 //! Meanwhile `proc_macro2` types may exist anywhere including non-macro code. 18 //! By developing foundational libraries like [syn] and [quote] against 19 //! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem 20 //! becomes easily applicable to many other use cases and we avoid 21 //! reimplementing non-macro equivalents of those libraries. 22 //! 23 //! - **Make procedural macros unit testable.** As a consequence of being 24 //! specific to procedural macros, nothing that uses `proc_macro` can be 25 //! executed from a unit test. In order for helper libraries or components of 26 //! a macro to be testable in isolation, they must be implemented using 27 //! `proc_macro2`. 28 //! 29 //! [syn]: https://github.com/dtolnay/syn 30 //! [quote]: https://github.com/dtolnay/quote 31 //! 32 //! # Usage 33 //! 34 //! The skeleton of a typical procedural macro typically looks like this: 35 //! 36 //! ``` 37 //! extern crate proc_macro; 38 //! 39 //! # const IGNORE: &str = stringify! { 40 //! #[proc_macro_derive(MyDerive)] 41 //! # }; 42 //! # #[cfg(wrap_proc_macro)] 43 //! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 44 //! let input = proc_macro2::TokenStream::from(input); 45 //! 46 //! let output: proc_macro2::TokenStream = { 47 //! /* transform input */ 48 //! # input 49 //! }; 50 //! 51 //! proc_macro::TokenStream::from(output) 52 //! } 53 //! ``` 54 //! 55 //! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to 56 //! propagate parse errors correctly back to the compiler when parsing fails. 57 //! 58 //! [`parse_macro_input!`]: https://docs.rs/syn/1.0/syn/macro.parse_macro_input.html 59 //! 60 //! # Unstable features 61 //! 62 //! The default feature set of proc-macro2 tracks the most recent stable 63 //! compiler API. Functionality in `proc_macro` that is not yet stable is not 64 //! exposed by proc-macro2 by default. 65 //! 66 //! To opt into the additional APIs available in the most recent nightly 67 //! compiler, the `procmacro2_semver_exempt` config flag must be passed to 68 //! rustc. We will polyfill those nightly-only APIs back to Rust 1.31.0. As 69 //! these are unstable APIs that track the nightly compiler, minor versions of 70 //! proc-macro2 may make breaking changes to them at any time. 71 //! 72 //! ```sh 73 //! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build 74 //! ``` 75 //! 76 //! Note that this must not only be done for your crate, but for any crate that 77 //! depends on your crate. This infectious nature is intentional, as it serves 78 //! as a reminder that you are outside of the normal semver guarantees. 79 //! 80 //! Semver exempt methods are marked as such in the proc-macro2 documentation. 81 //! 82 //! # Thread-Safety 83 //! 84 //! Most types in this crate are `!Sync` because the underlying compiler 85 //! types make use of thread-local memory, meaning they cannot be accessed from 86 //! a different thread. 87 88 // Proc-macro2 types in rustdoc of other crates get linked to here. 89 #![doc(html_root_url = "https://docs.rs/proc-macro2/1.0.53")] 90 #![cfg_attr( 91 any(proc_macro_span, super_unstable), 92 feature(proc_macro_span, proc_macro_span_shrink) 93 )] 94 #![cfg_attr(super_unstable, feature(proc_macro_def_site))] 95 #![cfg_attr(doc_cfg, feature(doc_cfg))] 96 #![allow( 97 clippy::cast_lossless, 98 clippy::cast_possible_truncation, 99 clippy::doc_markdown, 100 clippy::items_after_statements, 101 clippy::let_underscore_untyped, 102 clippy::manual_assert, 103 clippy::must_use_candidate, 104 clippy::needless_doctest_main, 105 clippy::return_self_not_must_use, 106 clippy::shadow_unrelated, 107 clippy::trivially_copy_pass_by_ref, 108 clippy::unnecessary_wraps, 109 clippy::unused_self, 110 clippy::used_underscore_binding, 111 clippy::vec_init_then_push 112 )] 113 114 #[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))] 115 compile_error! {"\ 116 Something is not right. If you've tried to turn on \ 117 procmacro2_semver_exempt, you need to ensure that it \ 118 is turned on for the compilation of the proc-macro2 \ 119 build script as well. 120 "} 121 122 #[cfg(use_proc_macro)] 123 extern crate proc_macro; 124 125 mod marker; 126 mod parse; 127 mod rcvec; 128 129 #[cfg(wrap_proc_macro)] 130 mod detection; 131 132 // Public for proc_macro2::fallback::force() and unforce(), but those are quite 133 // a niche use case so we omit it from rustdoc. 134 #[doc(hidden)] 135 pub mod fallback; 136 137 pub mod extra; 138 139 #[cfg(not(wrap_proc_macro))] 140 use crate::fallback as imp; 141 #[path = "wrapper.rs"] 142 #[cfg(wrap_proc_macro)] 143 mod imp; 144 145 #[cfg(span_locations)] 146 mod location; 147 148 use crate::extra::DelimSpan; 149 use crate::marker::Marker; 150 use core::cmp::Ordering; 151 use core::fmt::{self, Debug, Display}; 152 use core::hash::{Hash, Hasher}; 153 use core::iter::FromIterator; 154 use core::ops::RangeBounds; 155 use core::str::FromStr; 156 use std::error::Error; 157 #[cfg(procmacro2_semver_exempt)] 158 use std::path::PathBuf; 159 160 #[cfg(span_locations)] 161 pub use crate::location::LineColumn; 162 163 /// An abstract stream of tokens, or more concretely a sequence of token trees. 164 /// 165 /// This type provides interfaces for iterating over token trees and for 166 /// collecting token trees into one stream. 167 /// 168 /// Token stream is both the input and output of `#[proc_macro]`, 169 /// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions. 170 #[derive(Clone)] 171 pub struct TokenStream { 172 inner: imp::TokenStream, 173 _marker: Marker, 174 } 175 176 /// Error returned from `TokenStream::from_str`. 177 pub struct LexError { 178 inner: imp::LexError, 179 _marker: Marker, 180 } 181 182 impl TokenStream { _new(inner: imp::TokenStream) -> Self183 fn _new(inner: imp::TokenStream) -> Self { 184 TokenStream { 185 inner, 186 _marker: Marker, 187 } 188 } 189 _new_fallback(inner: fallback::TokenStream) -> Self190 fn _new_fallback(inner: fallback::TokenStream) -> Self { 191 TokenStream { 192 inner: inner.into(), 193 _marker: Marker, 194 } 195 } 196 197 /// Returns an empty `TokenStream` containing no token trees. new() -> Self198 pub fn new() -> Self { 199 TokenStream::_new(imp::TokenStream::new()) 200 } 201 202 /// Checks if this `TokenStream` is empty. is_empty(&self) -> bool203 pub fn is_empty(&self) -> bool { 204 self.inner.is_empty() 205 } 206 } 207 208 /// `TokenStream::default()` returns an empty stream, 209 /// i.e. this is equivalent with `TokenStream::new()`. 210 impl Default for TokenStream { default() -> Self211 fn default() -> Self { 212 TokenStream::new() 213 } 214 } 215 216 /// Attempts to break the string into tokens and parse those tokens into a token 217 /// stream. 218 /// 219 /// May fail for a number of reasons, for example, if the string contains 220 /// unbalanced delimiters or characters not existing in the language. 221 /// 222 /// NOTE: Some errors may cause panics instead of returning `LexError`. We 223 /// reserve the right to change these errors into `LexError`s later. 224 impl FromStr for TokenStream { 225 type Err = LexError; 226 from_str(src: &str) -> Result<TokenStream, LexError>227 fn from_str(src: &str) -> Result<TokenStream, LexError> { 228 let e = src.parse().map_err(|e| LexError { 229 inner: e, 230 _marker: Marker, 231 })?; 232 Ok(TokenStream::_new(e)) 233 } 234 } 235 236 #[cfg(use_proc_macro)] 237 impl From<proc_macro::TokenStream> for TokenStream { from(inner: proc_macro::TokenStream) -> Self238 fn from(inner: proc_macro::TokenStream) -> Self { 239 TokenStream::_new(inner.into()) 240 } 241 } 242 243 #[cfg(use_proc_macro)] 244 impl From<TokenStream> for proc_macro::TokenStream { from(inner: TokenStream) -> Self245 fn from(inner: TokenStream) -> Self { 246 inner.inner.into() 247 } 248 } 249 250 impl From<TokenTree> for TokenStream { from(token: TokenTree) -> Self251 fn from(token: TokenTree) -> Self { 252 TokenStream::_new(imp::TokenStream::from(token)) 253 } 254 } 255 256 impl Extend<TokenTree> for TokenStream { extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I)257 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) { 258 self.inner.extend(streams); 259 } 260 } 261 262 impl Extend<TokenStream> for TokenStream { extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I)263 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) { 264 self.inner 265 .extend(streams.into_iter().map(|stream| stream.inner)); 266 } 267 } 268 269 /// Collects a number of token trees into a single stream. 270 impl FromIterator<TokenTree> for TokenStream { from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self271 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self { 272 TokenStream::_new(streams.into_iter().collect()) 273 } 274 } 275 impl FromIterator<TokenStream> for TokenStream { from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self276 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self { 277 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect()) 278 } 279 } 280 281 /// Prints the token stream as a string that is supposed to be losslessly 282 /// convertible back into the same token stream (modulo spans), except for 283 /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative 284 /// numeric literals. 285 impl Display for TokenStream { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 287 Display::fmt(&self.inner, f) 288 } 289 } 290 291 /// Prints token in a form convenient for debugging. 292 impl Debug for TokenStream { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result293 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 294 Debug::fmt(&self.inner, f) 295 } 296 } 297 298 impl LexError { span(&self) -> Span299 pub fn span(&self) -> Span { 300 Span::_new(self.inner.span()) 301 } 302 } 303 304 impl Debug for LexError { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 306 Debug::fmt(&self.inner, f) 307 } 308 } 309 310 impl Display for LexError { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 312 Display::fmt(&self.inner, f) 313 } 314 } 315 316 impl Error for LexError {} 317 318 /// The source file of a given `Span`. 319 /// 320 /// This type is semver exempt and not exposed by default. 321 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 322 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] 323 #[derive(Clone, PartialEq, Eq)] 324 pub struct SourceFile { 325 inner: imp::SourceFile, 326 _marker: Marker, 327 } 328 329 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 330 impl SourceFile { _new(inner: imp::SourceFile) -> Self331 fn _new(inner: imp::SourceFile) -> Self { 332 SourceFile { 333 inner, 334 _marker: Marker, 335 } 336 } 337 338 /// Get the path to this source file. 339 /// 340 /// ### Note 341 /// 342 /// If the code span associated with this `SourceFile` was generated by an 343 /// external macro, this may not be an actual path on the filesystem. Use 344 /// [`is_real`] to check. 345 /// 346 /// Also note that even if `is_real` returns `true`, if 347 /// `--remap-path-prefix` was passed on the command line, the path as given 348 /// may not actually be valid. 349 /// 350 /// [`is_real`]: #method.is_real path(&self) -> PathBuf351 pub fn path(&self) -> PathBuf { 352 self.inner.path() 353 } 354 355 /// Returns `true` if this source file is a real source file, and not 356 /// generated by an external macro's expansion. is_real(&self) -> bool357 pub fn is_real(&self) -> bool { 358 self.inner.is_real() 359 } 360 } 361 362 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 363 impl Debug for SourceFile { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result364 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 365 Debug::fmt(&self.inner, f) 366 } 367 } 368 369 /// A region of source code, along with macro expansion information. 370 #[derive(Copy, Clone)] 371 pub struct Span { 372 inner: imp::Span, 373 _marker: Marker, 374 } 375 376 impl Span { _new(inner: imp::Span) -> Self377 fn _new(inner: imp::Span) -> Self { 378 Span { 379 inner, 380 _marker: Marker, 381 } 382 } 383 _new_fallback(inner: fallback::Span) -> Self384 fn _new_fallback(inner: fallback::Span) -> Self { 385 Span { 386 inner: inner.into(), 387 _marker: Marker, 388 } 389 } 390 391 /// The span of the invocation of the current procedural macro. 392 /// 393 /// Identifiers created with this span will be resolved as if they were 394 /// written directly at the macro call location (call-site hygiene) and 395 /// other code at the macro call site will be able to refer to them as well. call_site() -> Self396 pub fn call_site() -> Self { 397 Span::_new(imp::Span::call_site()) 398 } 399 400 /// The span located at the invocation of the procedural macro, but with 401 /// local variables, labels, and `$crate` resolved at the definition site 402 /// of the macro. This is the same hygiene behavior as `macro_rules`. 403 /// 404 /// This function requires Rust 1.45 or later. 405 #[cfg(not(no_hygiene))] mixed_site() -> Self406 pub fn mixed_site() -> Self { 407 Span::_new(imp::Span::mixed_site()) 408 } 409 410 /// A span that resolves at the macro definition site. 411 /// 412 /// This method is semver exempt and not exposed by default. 413 #[cfg(procmacro2_semver_exempt)] 414 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] def_site() -> Self415 pub fn def_site() -> Self { 416 Span::_new(imp::Span::def_site()) 417 } 418 419 /// Creates a new span with the same line/column information as `self` but 420 /// that resolves symbols as though it were at `other`. resolved_at(&self, other: Span) -> Span421 pub fn resolved_at(&self, other: Span) -> Span { 422 Span::_new(self.inner.resolved_at(other.inner)) 423 } 424 425 /// Creates a new span with the same name resolution behavior as `self` but 426 /// with the line/column information of `other`. located_at(&self, other: Span) -> Span427 pub fn located_at(&self, other: Span) -> Span { 428 Span::_new(self.inner.located_at(other.inner)) 429 } 430 431 /// Convert `proc_macro2::Span` to `proc_macro::Span`. 432 /// 433 /// This method is available when building with a nightly compiler, or when 434 /// building with rustc 1.29+ *without* semver exempt features. 435 /// 436 /// # Panics 437 /// 438 /// Panics if called from outside of a procedural macro. Unlike 439 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within 440 /// the context of a procedural macro invocation. 441 #[cfg(wrap_proc_macro)] unwrap(self) -> proc_macro::Span442 pub fn unwrap(self) -> proc_macro::Span { 443 self.inner.unwrap() 444 } 445 446 // Soft deprecated. Please use Span::unwrap. 447 #[cfg(wrap_proc_macro)] 448 #[doc(hidden)] unstable(self) -> proc_macro::Span449 pub fn unstable(self) -> proc_macro::Span { 450 self.unwrap() 451 } 452 453 /// The original source file into which this span points. 454 /// 455 /// This method is semver exempt and not exposed by default. 456 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 457 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] source_file(&self) -> SourceFile458 pub fn source_file(&self) -> SourceFile { 459 SourceFile::_new(self.inner.source_file()) 460 } 461 462 /// Get the starting line/column in the source file for this span. 463 /// 464 /// This method requires the `"span-locations"` feature to be enabled. 465 /// 466 /// When executing in a procedural macro context, the returned line/column 467 /// are only meaningful if compiled with a nightly toolchain. The stable 468 /// toolchain does not have this information available. When executing 469 /// outside of a procedural macro, such as main.rs or build.rs, the 470 /// line/column are always meaningful regardless of toolchain. 471 #[cfg(span_locations)] 472 #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] start(&self) -> LineColumn473 pub fn start(&self) -> LineColumn { 474 self.inner.start() 475 } 476 477 /// Get the ending line/column in the source file for this span. 478 /// 479 /// This method requires the `"span-locations"` feature to be enabled. 480 /// 481 /// When executing in a procedural macro context, the returned line/column 482 /// are only meaningful if compiled with a nightly toolchain. The stable 483 /// toolchain does not have this information available. When executing 484 /// outside of a procedural macro, such as main.rs or build.rs, the 485 /// line/column are always meaningful regardless of toolchain. 486 #[cfg(span_locations)] 487 #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] end(&self) -> LineColumn488 pub fn end(&self) -> LineColumn { 489 self.inner.end() 490 } 491 492 /// Creates an empty span pointing to directly before this span. 493 /// 494 /// This method is semver exempt and not exposed by default. 495 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 496 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] before(&self) -> Span497 pub fn before(&self) -> Span { 498 Span::_new(self.inner.before()) 499 } 500 501 /// Creates an empty span pointing to directly after this span. 502 /// 503 /// This method is semver exempt and not exposed by default. 504 #[cfg(all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] 505 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] after(&self) -> Span506 pub fn after(&self) -> Span { 507 Span::_new(self.inner.after()) 508 } 509 510 /// Create a new span encompassing `self` and `other`. 511 /// 512 /// Returns `None` if `self` and `other` are from different files. 513 /// 514 /// Warning: the underlying [`proc_macro::Span::join`] method is 515 /// nightly-only. When called from within a procedural macro not using a 516 /// nightly compiler, this method will always return `None`. 517 /// 518 /// [`proc_macro::Span::join`]: https://doc.rust-lang.org/proc_macro/struct.Span.html#method.join join(&self, other: Span) -> Option<Span>519 pub fn join(&self, other: Span) -> Option<Span> { 520 self.inner.join(other.inner).map(Span::_new) 521 } 522 523 /// Compares two spans to see if they're equal. 524 /// 525 /// This method is semver exempt and not exposed by default. 526 #[cfg(procmacro2_semver_exempt)] 527 #[cfg_attr(doc_cfg, doc(cfg(procmacro2_semver_exempt)))] eq(&self, other: &Span) -> bool528 pub fn eq(&self, other: &Span) -> bool { 529 self.inner.eq(&other.inner) 530 } 531 532 /// Returns the source text behind a span. This preserves the original 533 /// source code, including spaces and comments. It only returns a result if 534 /// the span corresponds to real source code. 535 /// 536 /// Note: The observable result of a macro should only rely on the tokens 537 /// and not on this source text. The result of this function is a best 538 /// effort to be used for diagnostics only. source_text(&self) -> Option<String>539 pub fn source_text(&self) -> Option<String> { 540 self.inner.source_text() 541 } 542 } 543 544 /// Prints a span in a form convenient for debugging. 545 impl Debug for Span { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 547 Debug::fmt(&self.inner, f) 548 } 549 } 550 551 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`). 552 #[derive(Clone)] 553 pub enum TokenTree { 554 /// A token stream surrounded by bracket delimiters. 555 Group(Group), 556 /// An identifier. 557 Ident(Ident), 558 /// A single punctuation character (`+`, `,`, `$`, etc.). 559 Punct(Punct), 560 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc. 561 Literal(Literal), 562 } 563 564 impl TokenTree { 565 /// Returns the span of this tree, delegating to the `span` method of 566 /// the contained token or a delimited stream. span(&self) -> Span567 pub fn span(&self) -> Span { 568 match self { 569 TokenTree::Group(t) => t.span(), 570 TokenTree::Ident(t) => t.span(), 571 TokenTree::Punct(t) => t.span(), 572 TokenTree::Literal(t) => t.span(), 573 } 574 } 575 576 /// Configures the span for *only this token*. 577 /// 578 /// Note that if this token is a `Group` then this method will not configure 579 /// the span of each of the internal tokens, this will simply delegate to 580 /// the `set_span` method of each variant. set_span(&mut self, span: Span)581 pub fn set_span(&mut self, span: Span) { 582 match self { 583 TokenTree::Group(t) => t.set_span(span), 584 TokenTree::Ident(t) => t.set_span(span), 585 TokenTree::Punct(t) => t.set_span(span), 586 TokenTree::Literal(t) => t.set_span(span), 587 } 588 } 589 } 590 591 impl From<Group> for TokenTree { from(g: Group) -> Self592 fn from(g: Group) -> Self { 593 TokenTree::Group(g) 594 } 595 } 596 597 impl From<Ident> for TokenTree { from(g: Ident) -> Self598 fn from(g: Ident) -> Self { 599 TokenTree::Ident(g) 600 } 601 } 602 603 impl From<Punct> for TokenTree { from(g: Punct) -> Self604 fn from(g: Punct) -> Self { 605 TokenTree::Punct(g) 606 } 607 } 608 609 impl From<Literal> for TokenTree { from(g: Literal) -> Self610 fn from(g: Literal) -> Self { 611 TokenTree::Literal(g) 612 } 613 } 614 615 /// Prints the token tree as a string that is supposed to be losslessly 616 /// convertible back into the same token tree (modulo spans), except for 617 /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative 618 /// numeric literals. 619 impl Display for TokenTree { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 621 match self { 622 TokenTree::Group(t) => Display::fmt(t, f), 623 TokenTree::Ident(t) => Display::fmt(t, f), 624 TokenTree::Punct(t) => Display::fmt(t, f), 625 TokenTree::Literal(t) => Display::fmt(t, f), 626 } 627 } 628 } 629 630 /// Prints token tree in a form convenient for debugging. 631 impl Debug for TokenTree { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 633 // Each of these has the name in the struct type in the derived debug, 634 // so don't bother with an extra layer of indirection 635 match self { 636 TokenTree::Group(t) => Debug::fmt(t, f), 637 TokenTree::Ident(t) => { 638 let mut debug = f.debug_struct("Ident"); 639 debug.field("sym", &format_args!("{}", t)); 640 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner); 641 debug.finish() 642 } 643 TokenTree::Punct(t) => Debug::fmt(t, f), 644 TokenTree::Literal(t) => Debug::fmt(t, f), 645 } 646 } 647 } 648 649 /// A delimited token stream. 650 /// 651 /// A `Group` internally contains a `TokenStream` which is surrounded by 652 /// `Delimiter`s. 653 #[derive(Clone)] 654 pub struct Group { 655 inner: imp::Group, 656 } 657 658 /// Describes how a sequence of token trees is delimited. 659 #[derive(Copy, Clone, Debug, Eq, PartialEq)] 660 pub enum Delimiter { 661 /// `( ... )` 662 Parenthesis, 663 /// `{ ... }` 664 Brace, 665 /// `[ ... ]` 666 Bracket, 667 /// `Ø ... Ø` 668 /// 669 /// An implicit delimiter, that may, for example, appear around tokens 670 /// coming from a "macro variable" `$var`. It is important to preserve 671 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`. 672 /// Implicit delimiters may not survive roundtrip of a token stream through 673 /// a string. 674 None, 675 } 676 677 impl Group { _new(inner: imp::Group) -> Self678 fn _new(inner: imp::Group) -> Self { 679 Group { inner } 680 } 681 _new_fallback(inner: fallback::Group) -> Self682 fn _new_fallback(inner: fallback::Group) -> Self { 683 Group { 684 inner: inner.into(), 685 } 686 } 687 688 /// Creates a new `Group` with the given delimiter and token stream. 689 /// 690 /// This constructor will set the span for this group to 691 /// `Span::call_site()`. To change the span you can use the `set_span` 692 /// method below. new(delimiter: Delimiter, stream: TokenStream) -> Self693 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { 694 Group { 695 inner: imp::Group::new(delimiter, stream.inner), 696 } 697 } 698 699 /// Returns the punctuation used as the delimiter for this group: a set of 700 /// parentheses, square brackets, or curly braces. delimiter(&self) -> Delimiter701 pub fn delimiter(&self) -> Delimiter { 702 self.inner.delimiter() 703 } 704 705 /// Returns the `TokenStream` of tokens that are delimited in this `Group`. 706 /// 707 /// Note that the returned token stream does not include the delimiter 708 /// returned above. stream(&self) -> TokenStream709 pub fn stream(&self) -> TokenStream { 710 TokenStream::_new(self.inner.stream()) 711 } 712 713 /// Returns the span for the delimiters of this token stream, spanning the 714 /// entire `Group`. 715 /// 716 /// ```text 717 /// pub fn span(&self) -> Span { 718 /// ^^^^^^^ 719 /// ``` span(&self) -> Span720 pub fn span(&self) -> Span { 721 Span::_new(self.inner.span()) 722 } 723 724 /// Returns the span pointing to the opening delimiter of this group. 725 /// 726 /// ```text 727 /// pub fn span_open(&self) -> Span { 728 /// ^ 729 /// ``` span_open(&self) -> Span730 pub fn span_open(&self) -> Span { 731 Span::_new(self.inner.span_open()) 732 } 733 734 /// Returns the span pointing to the closing delimiter of this group. 735 /// 736 /// ```text 737 /// pub fn span_close(&self) -> Span { 738 /// ^ 739 /// ``` span_close(&self) -> Span740 pub fn span_close(&self) -> Span { 741 Span::_new(self.inner.span_close()) 742 } 743 744 /// Returns an object that holds this group's `span_open()` and 745 /// `span_close()` together (in a more compact representation than holding 746 /// those 2 spans individually). delim_span(&self) -> DelimSpan747 pub fn delim_span(&self) -> DelimSpan { 748 DelimSpan::new(&self.inner) 749 } 750 751 /// Configures the span for this `Group`'s delimiters, but not its internal 752 /// tokens. 753 /// 754 /// This method will **not** set the span of all the internal tokens spanned 755 /// by this group, but rather it will only set the span of the delimiter 756 /// tokens at the level of the `Group`. set_span(&mut self, span: Span)757 pub fn set_span(&mut self, span: Span) { 758 self.inner.set_span(span.inner); 759 } 760 } 761 762 /// Prints the group as a string that should be losslessly convertible back 763 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s 764 /// with `Delimiter::None` delimiters. 765 impl Display for Group { fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result766 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 767 Display::fmt(&self.inner, formatter) 768 } 769 } 770 771 impl Debug for Group { fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result772 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 773 Debug::fmt(&self.inner, formatter) 774 } 775 } 776 777 /// A `Punct` is a single punctuation character like `+`, `-` or `#`. 778 /// 779 /// Multicharacter operators like `+=` are represented as two instances of 780 /// `Punct` with different forms of `Spacing` returned. 781 #[derive(Clone)] 782 pub struct Punct { 783 ch: char, 784 spacing: Spacing, 785 span: Span, 786 } 787 788 /// Whether a `Punct` is followed immediately by another `Punct` or followed by 789 /// another token or whitespace. 790 #[derive(Copy, Clone, Debug, Eq, PartialEq)] 791 pub enum Spacing { 792 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`. 793 Alone, 794 /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`. 795 /// 796 /// Additionally, single quote `'` can join with identifiers to form 797 /// lifetimes `'ident`. 798 Joint, 799 } 800 801 impl Punct { 802 /// Creates a new `Punct` from the given character and spacing. 803 /// 804 /// The `ch` argument must be a valid punctuation character permitted by the 805 /// language, otherwise the function will panic. 806 /// 807 /// The returned `Punct` will have the default span of `Span::call_site()` 808 /// which can be further configured with the `set_span` method below. new(ch: char, spacing: Spacing) -> Self809 pub fn new(ch: char, spacing: Spacing) -> Self { 810 Punct { 811 ch, 812 spacing, 813 span: Span::call_site(), 814 } 815 } 816 817 /// Returns the value of this punctuation character as `char`. as_char(&self) -> char818 pub fn as_char(&self) -> char { 819 self.ch 820 } 821 822 /// Returns the spacing of this punctuation character, indicating whether 823 /// it's immediately followed by another `Punct` in the token stream, so 824 /// they can potentially be combined into a multicharacter operator 825 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`) 826 /// so the operator has certainly ended. spacing(&self) -> Spacing827 pub fn spacing(&self) -> Spacing { 828 self.spacing 829 } 830 831 /// Returns the span for this punctuation character. span(&self) -> Span832 pub fn span(&self) -> Span { 833 self.span 834 } 835 836 /// Configure the span for this punctuation character. set_span(&mut self, span: Span)837 pub fn set_span(&mut self, span: Span) { 838 self.span = span; 839 } 840 } 841 842 /// Prints the punctuation character as a string that should be losslessly 843 /// convertible back into the same character. 844 impl Display for Punct { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 846 Display::fmt(&self.ch, f) 847 } 848 } 849 850 impl Debug for Punct { fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result851 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 852 let mut debug = fmt.debug_struct("Punct"); 853 debug.field("char", &self.ch); 854 debug.field("spacing", &self.spacing); 855 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner); 856 debug.finish() 857 } 858 } 859 860 /// A word of Rust code, which may be a keyword or legal variable name. 861 /// 862 /// An identifier consists of at least one Unicode code point, the first of 863 /// which has the XID_Start property and the rest of which have the XID_Continue 864 /// property. 865 /// 866 /// - The empty string is not an identifier. Use `Option<Ident>`. 867 /// - A lifetime is not an identifier. Use `syn::Lifetime` instead. 868 /// 869 /// An identifier constructed with `Ident::new` is permitted to be a Rust 870 /// keyword, though parsing one through its [`Parse`] implementation rejects 871 /// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the 872 /// behaviour of `Ident::new`. 873 /// 874 /// [`Parse`]: https://docs.rs/syn/1.0/syn/parse/trait.Parse.html 875 /// 876 /// # Examples 877 /// 878 /// A new ident can be created from a string using the `Ident::new` function. 879 /// A span must be provided explicitly which governs the name resolution 880 /// behavior of the resulting identifier. 881 /// 882 /// ``` 883 /// use proc_macro2::{Ident, Span}; 884 /// 885 /// fn main() { 886 /// let call_ident = Ident::new("calligraphy", Span::call_site()); 887 /// 888 /// println!("{}", call_ident); 889 /// } 890 /// ``` 891 /// 892 /// An ident can be interpolated into a token stream using the `quote!` macro. 893 /// 894 /// ``` 895 /// use proc_macro2::{Ident, Span}; 896 /// use quote::quote; 897 /// 898 /// fn main() { 899 /// let ident = Ident::new("demo", Span::call_site()); 900 /// 901 /// // Create a variable binding whose name is this ident. 902 /// let expanded = quote! { let #ident = 10; }; 903 /// 904 /// // Create a variable binding with a slightly different name. 905 /// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site()); 906 /// let expanded = quote! { let #temp_ident = 10; }; 907 /// } 908 /// ``` 909 /// 910 /// A string representation of the ident is available through the `to_string()` 911 /// method. 912 /// 913 /// ``` 914 /// # use proc_macro2::{Ident, Span}; 915 /// # 916 /// # let ident = Ident::new("another_identifier", Span::call_site()); 917 /// # 918 /// // Examine the ident as a string. 919 /// let ident_string = ident.to_string(); 920 /// if ident_string.len() > 60 { 921 /// println!("Very long identifier: {}", ident_string) 922 /// } 923 /// ``` 924 #[derive(Clone)] 925 pub struct Ident { 926 inner: imp::Ident, 927 _marker: Marker, 928 } 929 930 impl Ident { _new(inner: imp::Ident) -> Self931 fn _new(inner: imp::Ident) -> Self { 932 Ident { 933 inner, 934 _marker: Marker, 935 } 936 } 937 938 /// Creates a new `Ident` with the given `string` as well as the specified 939 /// `span`. 940 /// 941 /// The `string` argument must be a valid identifier permitted by the 942 /// language, otherwise the function will panic. 943 /// 944 /// Note that `span`, currently in rustc, configures the hygiene information 945 /// for this identifier. 946 /// 947 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" 948 /// hygiene meaning that identifiers created with this span will be resolved 949 /// as if they were written directly at the location of the macro call, and 950 /// other code at the macro call site will be able to refer to them as well. 951 /// 952 /// Later spans like `Span::def_site()` will allow to opt-in to 953 /// "definition-site" hygiene meaning that identifiers created with this 954 /// span will be resolved at the location of the macro definition and other 955 /// code at the macro call site will not be able to refer to them. 956 /// 957 /// Due to the current importance of hygiene this constructor, unlike other 958 /// tokens, requires a `Span` to be specified at construction. 959 /// 960 /// # Panics 961 /// 962 /// Panics if the input string is neither a keyword nor a legal variable 963 /// name. If you are not sure whether the string contains an identifier and 964 /// need to handle an error case, use 965 /// <a href="https://docs.rs/syn/1.0/syn/fn.parse_str.html"><code 966 /// style="padding-right:0;">syn::parse_str</code></a><code 967 /// style="padding-left:0;">::<Ident></code> 968 /// rather than `Ident::new`. new(string: &str, span: Span) -> Self969 pub fn new(string: &str, span: Span) -> Self { 970 Ident::_new(imp::Ident::new(string, span.inner)) 971 } 972 973 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The 974 /// `string` argument must be a valid identifier permitted by the language 975 /// (including keywords, e.g. `fn`). Keywords which are usable in path 976 /// segments (e.g. `self`, `super`) are not supported, and will cause a 977 /// panic. new_raw(string: &str, span: Span) -> Self978 pub fn new_raw(string: &str, span: Span) -> Self { 979 Ident::_new_raw(string, span) 980 } 981 _new_raw(string: &str, span: Span) -> Self982 fn _new_raw(string: &str, span: Span) -> Self { 983 Ident::_new(imp::Ident::new_raw(string, span.inner)) 984 } 985 986 /// Returns the span of this `Ident`. span(&self) -> Span987 pub fn span(&self) -> Span { 988 Span::_new(self.inner.span()) 989 } 990 991 /// Configures the span of this `Ident`, possibly changing its hygiene 992 /// context. set_span(&mut self, span: Span)993 pub fn set_span(&mut self, span: Span) { 994 self.inner.set_span(span.inner); 995 } 996 } 997 998 impl PartialEq for Ident { eq(&self, other: &Ident) -> bool999 fn eq(&self, other: &Ident) -> bool { 1000 self.inner == other.inner 1001 } 1002 } 1003 1004 impl<T> PartialEq<T> for Ident 1005 where 1006 T: ?Sized + AsRef<str>, 1007 { eq(&self, other: &T) -> bool1008 fn eq(&self, other: &T) -> bool { 1009 self.inner == other 1010 } 1011 } 1012 1013 impl Eq for Ident {} 1014 1015 impl PartialOrd for Ident { partial_cmp(&self, other: &Ident) -> Option<Ordering>1016 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> { 1017 Some(self.cmp(other)) 1018 } 1019 } 1020 1021 impl Ord for Ident { cmp(&self, other: &Ident) -> Ordering1022 fn cmp(&self, other: &Ident) -> Ordering { 1023 self.to_string().cmp(&other.to_string()) 1024 } 1025 } 1026 1027 impl Hash for Ident { hash<H: Hasher>(&self, hasher: &mut H)1028 fn hash<H: Hasher>(&self, hasher: &mut H) { 1029 self.to_string().hash(hasher); 1030 } 1031 } 1032 1033 /// Prints the identifier as a string that should be losslessly convertible back 1034 /// into the same identifier. 1035 impl Display for Ident { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1036 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1037 Display::fmt(&self.inner, f) 1038 } 1039 } 1040 1041 impl Debug for Ident { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1042 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1043 Debug::fmt(&self.inner, f) 1044 } 1045 } 1046 1047 /// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`), 1048 /// byte character (`b'a'`), an integer or floating point number with or without 1049 /// a suffix (`1`, `1u8`, `2.3`, `2.3f32`). 1050 /// 1051 /// Boolean literals like `true` and `false` do not belong here, they are 1052 /// `Ident`s. 1053 #[derive(Clone)] 1054 pub struct Literal { 1055 inner: imp::Literal, 1056 _marker: Marker, 1057 } 1058 1059 macro_rules! suffixed_int_literals { 1060 ($($name:ident => $kind:ident,)*) => ($( 1061 /// Creates a new suffixed integer literal with the specified value. 1062 /// 1063 /// This function will create an integer like `1u32` where the integer 1064 /// value specified is the first part of the token and the integral is 1065 /// also suffixed at the end. Literals created from negative numbers may 1066 /// not survive roundtrips through `TokenStream` or strings and may be 1067 /// broken into two tokens (`-` and positive literal). 1068 /// 1069 /// Literals created through this method have the `Span::call_site()` 1070 /// span by default, which can be configured with the `set_span` method 1071 /// below. 1072 pub fn $name(n: $kind) -> Literal { 1073 Literal::_new(imp::Literal::$name(n)) 1074 } 1075 )*) 1076 } 1077 1078 macro_rules! unsuffixed_int_literals { 1079 ($($name:ident => $kind:ident,)*) => ($( 1080 /// Creates a new unsuffixed integer literal with the specified value. 1081 /// 1082 /// This function will create an integer like `1` where the integer 1083 /// value specified is the first part of the token. No suffix is 1084 /// specified on this token, meaning that invocations like 1085 /// `Literal::i8_unsuffixed(1)` are equivalent to 1086 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers 1087 /// may not survive roundtrips through `TokenStream` or strings and may 1088 /// be broken into two tokens (`-` and positive literal). 1089 /// 1090 /// Literals created through this method have the `Span::call_site()` 1091 /// span by default, which can be configured with the `set_span` method 1092 /// below. 1093 pub fn $name(n: $kind) -> Literal { 1094 Literal::_new(imp::Literal::$name(n)) 1095 } 1096 )*) 1097 } 1098 1099 impl Literal { _new(inner: imp::Literal) -> Self1100 fn _new(inner: imp::Literal) -> Self { 1101 Literal { 1102 inner, 1103 _marker: Marker, 1104 } 1105 } 1106 _new_fallback(inner: fallback::Literal) -> Self1107 fn _new_fallback(inner: fallback::Literal) -> Self { 1108 Literal { 1109 inner: inner.into(), 1110 _marker: Marker, 1111 } 1112 } 1113 1114 suffixed_int_literals! { 1115 u8_suffixed => u8, 1116 u16_suffixed => u16, 1117 u32_suffixed => u32, 1118 u64_suffixed => u64, 1119 u128_suffixed => u128, 1120 usize_suffixed => usize, 1121 i8_suffixed => i8, 1122 i16_suffixed => i16, 1123 i32_suffixed => i32, 1124 i64_suffixed => i64, 1125 i128_suffixed => i128, 1126 isize_suffixed => isize, 1127 } 1128 1129 unsuffixed_int_literals! { 1130 u8_unsuffixed => u8, 1131 u16_unsuffixed => u16, 1132 u32_unsuffixed => u32, 1133 u64_unsuffixed => u64, 1134 u128_unsuffixed => u128, 1135 usize_unsuffixed => usize, 1136 i8_unsuffixed => i8, 1137 i16_unsuffixed => i16, 1138 i32_unsuffixed => i32, 1139 i64_unsuffixed => i64, 1140 i128_unsuffixed => i128, 1141 isize_unsuffixed => isize, 1142 } 1143 1144 /// Creates a new unsuffixed floating-point literal. 1145 /// 1146 /// This constructor is similar to those like `Literal::i8_unsuffixed` where 1147 /// the float's value is emitted directly into the token but no suffix is 1148 /// used, so it may be inferred to be a `f64` later in the compiler. 1149 /// Literals created from negative numbers may not survive round-trips 1150 /// through `TokenStream` or strings and may be broken into two tokens (`-` 1151 /// and positive literal). 1152 /// 1153 /// # Panics 1154 /// 1155 /// This function requires that the specified float is finite, for example 1156 /// if it is infinity or NaN this function will panic. f64_unsuffixed(f: f64) -> Literal1157 pub fn f64_unsuffixed(f: f64) -> Literal { 1158 assert!(f.is_finite()); 1159 Literal::_new(imp::Literal::f64_unsuffixed(f)) 1160 } 1161 1162 /// Creates a new suffixed floating-point literal. 1163 /// 1164 /// This constructor will create a literal like `1.0f64` where the value 1165 /// specified is the preceding part of the token and `f64` is the suffix of 1166 /// the token. This token will always be inferred to be an `f64` in the 1167 /// compiler. Literals created from negative numbers may not survive 1168 /// round-trips through `TokenStream` or strings and may be broken into two 1169 /// tokens (`-` and positive literal). 1170 /// 1171 /// # Panics 1172 /// 1173 /// This function requires that the specified float is finite, for example 1174 /// if it is infinity or NaN this function will panic. f64_suffixed(f: f64) -> Literal1175 pub fn f64_suffixed(f: f64) -> Literal { 1176 assert!(f.is_finite()); 1177 Literal::_new(imp::Literal::f64_suffixed(f)) 1178 } 1179 1180 /// Creates a new unsuffixed floating-point literal. 1181 /// 1182 /// This constructor is similar to those like `Literal::i8_unsuffixed` where 1183 /// the float's value is emitted directly into the token but no suffix is 1184 /// used, so it may be inferred to be a `f64` later in the compiler. 1185 /// Literals created from negative numbers may not survive round-trips 1186 /// through `TokenStream` or strings and may be broken into two tokens (`-` 1187 /// and positive literal). 1188 /// 1189 /// # Panics 1190 /// 1191 /// This function requires that the specified float is finite, for example 1192 /// if it is infinity or NaN this function will panic. f32_unsuffixed(f: f32) -> Literal1193 pub fn f32_unsuffixed(f: f32) -> Literal { 1194 assert!(f.is_finite()); 1195 Literal::_new(imp::Literal::f32_unsuffixed(f)) 1196 } 1197 1198 /// Creates a new suffixed floating-point literal. 1199 /// 1200 /// This constructor will create a literal like `1.0f32` where the value 1201 /// specified is the preceding part of the token and `f32` is the suffix of 1202 /// the token. This token will always be inferred to be an `f32` in the 1203 /// compiler. Literals created from negative numbers may not survive 1204 /// round-trips through `TokenStream` or strings and may be broken into two 1205 /// tokens (`-` and positive literal). 1206 /// 1207 /// # Panics 1208 /// 1209 /// This function requires that the specified float is finite, for example 1210 /// if it is infinity or NaN this function will panic. f32_suffixed(f: f32) -> Literal1211 pub fn f32_suffixed(f: f32) -> Literal { 1212 assert!(f.is_finite()); 1213 Literal::_new(imp::Literal::f32_suffixed(f)) 1214 } 1215 1216 /// String literal. string(string: &str) -> Literal1217 pub fn string(string: &str) -> Literal { 1218 Literal::_new(imp::Literal::string(string)) 1219 } 1220 1221 /// Character literal. character(ch: char) -> Literal1222 pub fn character(ch: char) -> Literal { 1223 Literal::_new(imp::Literal::character(ch)) 1224 } 1225 1226 /// Byte string literal. byte_string(s: &[u8]) -> Literal1227 pub fn byte_string(s: &[u8]) -> Literal { 1228 Literal::_new(imp::Literal::byte_string(s)) 1229 } 1230 1231 /// Returns the span encompassing this literal. span(&self) -> Span1232 pub fn span(&self) -> Span { 1233 Span::_new(self.inner.span()) 1234 } 1235 1236 /// Configures the span associated for this literal. set_span(&mut self, span: Span)1237 pub fn set_span(&mut self, span: Span) { 1238 self.inner.set_span(span.inner); 1239 } 1240 1241 /// Returns a `Span` that is a subset of `self.span()` containing only 1242 /// the source bytes in range `range`. Returns `None` if the would-be 1243 /// trimmed span is outside the bounds of `self`. 1244 /// 1245 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is 1246 /// nightly-only. When called from within a procedural macro not using a 1247 /// nightly compiler, this method will always return `None`. 1248 /// 1249 /// [`proc_macro::Literal::subspan`]: https://doc.rust-lang.org/proc_macro/struct.Literal.html#method.subspan subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span>1250 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> { 1251 self.inner.subspan(range).map(Span::_new) 1252 } 1253 1254 // Intended for the `quote!` macro to use when constructing a proc-macro2 1255 // token out of a macro_rules $:literal token, which is already known to be 1256 // a valid literal. This avoids reparsing/validating the literal's string 1257 // representation. This is not public API other than for quote. 1258 #[doc(hidden)] from_str_unchecked(repr: &str) -> Self1259 pub unsafe fn from_str_unchecked(repr: &str) -> Self { 1260 Literal::_new(imp::Literal::from_str_unchecked(repr)) 1261 } 1262 } 1263 1264 impl FromStr for Literal { 1265 type Err = LexError; 1266 from_str(repr: &str) -> Result<Self, LexError>1267 fn from_str(repr: &str) -> Result<Self, LexError> { 1268 repr.parse().map(Literal::_new).map_err(|inner| LexError { 1269 inner, 1270 _marker: Marker, 1271 }) 1272 } 1273 } 1274 1275 impl Debug for Literal { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1277 Debug::fmt(&self.inner, f) 1278 } 1279 } 1280 1281 impl Display for Literal { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1283 Display::fmt(&self.inner, f) 1284 } 1285 } 1286 1287 /// Public implementation details for the `TokenStream` type, such as iterators. 1288 pub mod token_stream { 1289 use crate::marker::Marker; 1290 use crate::{imp, TokenTree}; 1291 use core::fmt::{self, Debug}; 1292 1293 pub use crate::TokenStream; 1294 1295 /// An iterator over `TokenStream`'s `TokenTree`s. 1296 /// 1297 /// The iteration is "shallow", e.g. the iterator doesn't recurse into 1298 /// delimited groups, and returns whole groups as token trees. 1299 #[derive(Clone)] 1300 pub struct IntoIter { 1301 inner: imp::TokenTreeIter, 1302 _marker: Marker, 1303 } 1304 1305 impl Iterator for IntoIter { 1306 type Item = TokenTree; 1307 next(&mut self) -> Option<TokenTree>1308 fn next(&mut self) -> Option<TokenTree> { 1309 self.inner.next() 1310 } 1311 size_hint(&self) -> (usize, Option<usize>)1312 fn size_hint(&self) -> (usize, Option<usize>) { 1313 self.inner.size_hint() 1314 } 1315 } 1316 1317 impl Debug for IntoIter { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1318 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1319 f.write_str("TokenStream ")?; 1320 f.debug_list().entries(self.clone()).finish() 1321 } 1322 } 1323 1324 impl IntoIterator for TokenStream { 1325 type Item = TokenTree; 1326 type IntoIter = IntoIter; 1327 into_iter(self) -> IntoIter1328 fn into_iter(self) -> IntoIter { 1329 IntoIter { 1330 inner: self.inner.into_iter(), 1331 _marker: Marker, 1332 } 1333 } 1334 } 1335 } 1336