1 // SPDX-License-Identifier: Apache-2.0 OR MIT 2 3 //! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate) 4 //! 5 //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 6 //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 7 //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 8 //! 9 //! <br> 10 //! 11 //! A wrapper around the procedural macro API of the compiler's [`proc_macro`] 12 //! crate. This library serves two purposes: 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/2.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.56.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.101")] 90 #![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))] 91 #![cfg_attr(super_unstable, feature(proc_macro_def_site))] 92 #![cfg_attr(docsrs, feature(doc_cfg))] 93 #![deny(unsafe_op_in_unsafe_fn)] 94 #![allow( 95 clippy::cast_lossless, 96 clippy::cast_possible_truncation, 97 clippy::checked_conversions, 98 clippy::doc_markdown, 99 clippy::elidable_lifetime_names, 100 clippy::incompatible_msrv, 101 clippy::items_after_statements, 102 clippy::iter_without_into_iter, 103 clippy::let_underscore_untyped, 104 clippy::manual_assert, 105 clippy::manual_range_contains, 106 clippy::missing_panics_doc, 107 clippy::missing_safety_doc, 108 clippy::must_use_candidate, 109 clippy::needless_doctest_main, 110 clippy::needless_lifetimes, 111 clippy::new_without_default, 112 clippy::return_self_not_must_use, 113 clippy::shadow_unrelated, 114 clippy::trivially_copy_pass_by_ref, 115 clippy::unnecessary_wraps, 116 clippy::unused_self, 117 clippy::used_underscore_binding, 118 clippy::vec_init_then_push 119 )] 120 #![allow(unknown_lints, mismatched_lifetime_syntaxes)] 121 122 #[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))] 123 compile_error! {"\ 124 Something is not right. If you've tried to turn on \ 125 procmacro2_semver_exempt, you need to ensure that it \ 126 is turned on for the compilation of the proc-macro2 \ 127 build script as well. 128 "} 129 130 #[cfg(all( 131 procmacro2_nightly_testing, 132 feature = "proc-macro", 133 not(proc_macro_span) 134 ))] 135 compile_error! {"\ 136 Build script probe failed to compile. 137 "} 138 139 extern crate alloc; 140 141 #[cfg(feature = "proc-macro")] 142 extern crate proc_macro; 143 144 mod marker; 145 mod parse; 146 mod probe; 147 mod rcvec; 148 149 #[cfg(wrap_proc_macro)] 150 mod detection; 151 152 // Public for proc_macro2::fallback::force() and unforce(), but those are quite 153 // a niche use case so we omit it from rustdoc. 154 #[doc(hidden)] 155 pub mod fallback; 156 157 pub mod extra; 158 159 #[cfg(not(wrap_proc_macro))] 160 use crate::fallback as imp; 161 #[path = "wrapper.rs"] 162 #[cfg(wrap_proc_macro)] 163 mod imp; 164 165 #[cfg(span_locations)] 166 mod location; 167 168 use crate::extra::DelimSpan; 169 use crate::marker::{ProcMacroAutoTraits, MARKER}; 170 use core::cmp::Ordering; 171 use core::fmt::{self, Debug, Display}; 172 use core::hash::{Hash, Hasher}; 173 #[cfg(span_locations)] 174 use core::ops::Range; 175 use core::ops::RangeBounds; 176 use core::str::FromStr; 177 use std::error::Error; 178 use std::ffi::CStr; 179 #[cfg(span_locations)] 180 use std::path::PathBuf; 181 182 #[cfg(span_locations)] 183 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] 184 pub use crate::location::LineColumn; 185 186 /// An abstract stream of tokens, or more concretely a sequence of token trees. 187 /// 188 /// This type provides interfaces for iterating over token trees and for 189 /// collecting token trees into one stream. 190 /// 191 /// Token stream is both the input and output of `#[proc_macro]`, 192 /// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions. 193 #[derive(Clone)] 194 pub struct TokenStream { 195 inner: imp::TokenStream, 196 _marker: ProcMacroAutoTraits, 197 } 198 199 /// Error returned from `TokenStream::from_str`. 200 pub struct LexError { 201 inner: imp::LexError, 202 _marker: ProcMacroAutoTraits, 203 } 204 205 impl TokenStream { _new(inner: imp::TokenStream) -> Self206 fn _new(inner: imp::TokenStream) -> Self { 207 TokenStream { 208 inner, 209 _marker: MARKER, 210 } 211 } 212 _new_fallback(inner: fallback::TokenStream) -> Self213 fn _new_fallback(inner: fallback::TokenStream) -> Self { 214 TokenStream { 215 inner: imp::TokenStream::from(inner), 216 _marker: MARKER, 217 } 218 } 219 220 /// Returns an empty `TokenStream` containing no token trees. new() -> Self221 pub fn new() -> Self { 222 TokenStream::_new(imp::TokenStream::new()) 223 } 224 225 /// Checks if this `TokenStream` is empty. is_empty(&self) -> bool226 pub fn is_empty(&self) -> bool { 227 self.inner.is_empty() 228 } 229 } 230 231 /// `TokenStream::default()` returns an empty stream, 232 /// i.e. this is equivalent with `TokenStream::new()`. 233 impl Default for TokenStream { default() -> Self234 fn default() -> Self { 235 TokenStream::new() 236 } 237 } 238 239 /// Attempts to break the string into tokens and parse those tokens into a token 240 /// stream. 241 /// 242 /// May fail for a number of reasons, for example, if the string contains 243 /// unbalanced delimiters or characters not existing in the language. 244 /// 245 /// NOTE: Some errors may cause panics instead of returning `LexError`. We 246 /// reserve the right to change these errors into `LexError`s later. 247 impl FromStr for TokenStream { 248 type Err = LexError; 249 from_str(src: &str) -> Result<TokenStream, LexError>250 fn from_str(src: &str) -> Result<TokenStream, LexError> { 251 match imp::TokenStream::from_str_checked(src) { 252 Ok(tokens) => Ok(TokenStream::_new(tokens)), 253 Err(lex) => Err(LexError { 254 inner: lex, 255 _marker: MARKER, 256 }), 257 } 258 } 259 } 260 261 #[cfg(feature = "proc-macro")] 262 #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] 263 impl From<proc_macro::TokenStream> for TokenStream { from(inner: proc_macro::TokenStream) -> Self264 fn from(inner: proc_macro::TokenStream) -> Self { 265 TokenStream::_new(imp::TokenStream::from(inner)) 266 } 267 } 268 269 #[cfg(feature = "proc-macro")] 270 #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] 271 impl From<TokenStream> for proc_macro::TokenStream { from(inner: TokenStream) -> Self272 fn from(inner: TokenStream) -> Self { 273 proc_macro::TokenStream::from(inner.inner) 274 } 275 } 276 277 impl From<TokenTree> for TokenStream { from(token: TokenTree) -> Self278 fn from(token: TokenTree) -> Self { 279 TokenStream::_new(imp::TokenStream::from(token)) 280 } 281 } 282 283 impl Extend<TokenTree> for TokenStream { extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I)284 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) { 285 self.inner.extend(streams); 286 } 287 } 288 289 impl Extend<TokenStream> for TokenStream { extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I)290 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) { 291 self.inner 292 .extend(streams.into_iter().map(|stream| stream.inner)); 293 } 294 } 295 296 /// Collects a number of token trees into a single stream. 297 impl FromIterator<TokenTree> for TokenStream { from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self298 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self { 299 TokenStream::_new(streams.into_iter().collect()) 300 } 301 } 302 impl FromIterator<TokenStream> for TokenStream { from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self303 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self { 304 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect()) 305 } 306 } 307 308 /// Prints the token stream as a string that is supposed to be losslessly 309 /// convertible back into the same token stream (modulo spans), except for 310 /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative 311 /// numeric literals. 312 impl Display for TokenStream { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 314 Display::fmt(&self.inner, f) 315 } 316 } 317 318 /// Prints token in a form convenient for debugging. 319 impl Debug for TokenStream { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 321 Debug::fmt(&self.inner, f) 322 } 323 } 324 325 impl LexError { span(&self) -> Span326 pub fn span(&self) -> Span { 327 Span::_new(self.inner.span()) 328 } 329 } 330 331 impl Debug for LexError { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 333 Debug::fmt(&self.inner, f) 334 } 335 } 336 337 impl Display for LexError { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 339 Display::fmt(&self.inner, f) 340 } 341 } 342 343 impl Error for LexError {} 344 345 /// A region of source code, along with macro expansion information. 346 #[derive(Copy, Clone)] 347 pub struct Span { 348 inner: imp::Span, 349 _marker: ProcMacroAutoTraits, 350 } 351 352 impl Span { _new(inner: imp::Span) -> Self353 fn _new(inner: imp::Span) -> Self { 354 Span { 355 inner, 356 _marker: MARKER, 357 } 358 } 359 _new_fallback(inner: fallback::Span) -> Self360 fn _new_fallback(inner: fallback::Span) -> Self { 361 Span { 362 inner: imp::Span::from(inner), 363 _marker: MARKER, 364 } 365 } 366 367 /// The span of the invocation of the current procedural macro. 368 /// 369 /// Identifiers created with this span will be resolved as if they were 370 /// written directly at the macro call location (call-site hygiene) and 371 /// other code at the macro call site will be able to refer to them as well. call_site() -> Self372 pub fn call_site() -> Self { 373 Span::_new(imp::Span::call_site()) 374 } 375 376 /// The span located at the invocation of the procedural macro, but with 377 /// local variables, labels, and `$crate` resolved at the definition site 378 /// of the macro. This is the same hygiene behavior as `macro_rules`. mixed_site() -> Self379 pub fn mixed_site() -> Self { 380 Span::_new(imp::Span::mixed_site()) 381 } 382 383 /// A span that resolves at the macro definition site. 384 /// 385 /// This method is semver exempt and not exposed by default. 386 #[cfg(procmacro2_semver_exempt)] 387 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] def_site() -> Self388 pub fn def_site() -> Self { 389 Span::_new(imp::Span::def_site()) 390 } 391 392 /// Creates a new span with the same line/column information as `self` but 393 /// that resolves symbols as though it were at `other`. resolved_at(&self, other: Span) -> Span394 pub fn resolved_at(&self, other: Span) -> Span { 395 Span::_new(self.inner.resolved_at(other.inner)) 396 } 397 398 /// Creates a new span with the same name resolution behavior as `self` but 399 /// with the line/column information of `other`. located_at(&self, other: Span) -> Span400 pub fn located_at(&self, other: Span) -> Span { 401 Span::_new(self.inner.located_at(other.inner)) 402 } 403 404 /// Convert `proc_macro2::Span` to `proc_macro::Span`. 405 /// 406 /// This method is available when building with a nightly compiler, or when 407 /// building with rustc 1.29+ *without* semver exempt features. 408 /// 409 /// # Panics 410 /// 411 /// Panics if called from outside of a procedural macro. Unlike 412 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within 413 /// the context of a procedural macro invocation. 414 #[cfg(wrap_proc_macro)] unwrap(self) -> proc_macro::Span415 pub fn unwrap(self) -> proc_macro::Span { 416 self.inner.unwrap() 417 } 418 419 // Soft deprecated. Please use Span::unwrap. 420 #[cfg(wrap_proc_macro)] 421 #[doc(hidden)] unstable(self) -> proc_macro::Span422 pub fn unstable(self) -> proc_macro::Span { 423 self.unwrap() 424 } 425 426 /// Returns the span's byte position range in the source file. 427 /// 428 /// This method requires the `"span-locations"` feature to be enabled. 429 /// 430 /// When executing in a procedural macro context, the returned range is only 431 /// accurate if compiled with a nightly toolchain. The stable toolchain does 432 /// not have this information available. When executing outside of a 433 /// procedural macro, such as main.rs or build.rs, the byte range is always 434 /// accurate regardless of toolchain. 435 #[cfg(span_locations)] 436 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] byte_range(&self) -> Range<usize>437 pub fn byte_range(&self) -> Range<usize> { 438 self.inner.byte_range() 439 } 440 441 /// Get the starting line/column in the source file for this span. 442 /// 443 /// This method requires the `"span-locations"` feature to be enabled. 444 /// 445 /// When executing in a procedural macro context, the returned line/column 446 /// are only meaningful if compiled with a nightly toolchain. The stable 447 /// toolchain does not have this information available. When executing 448 /// outside of a procedural macro, such as main.rs or build.rs, the 449 /// line/column are always meaningful regardless of toolchain. 450 #[cfg(span_locations)] 451 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] start(&self) -> LineColumn452 pub fn start(&self) -> LineColumn { 453 self.inner.start() 454 } 455 456 /// Get the ending line/column in the source file for this span. 457 /// 458 /// This method requires the `"span-locations"` feature to be enabled. 459 /// 460 /// When executing in a procedural macro context, the returned line/column 461 /// are only meaningful if compiled with a nightly toolchain. The stable 462 /// toolchain does not have this information available. When executing 463 /// outside of a procedural macro, such as main.rs or build.rs, the 464 /// line/column are always meaningful regardless of toolchain. 465 #[cfg(span_locations)] 466 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] end(&self) -> LineColumn467 pub fn end(&self) -> LineColumn { 468 self.inner.end() 469 } 470 471 /// The path to the source file in which this span occurs, for display 472 /// purposes. 473 /// 474 /// This might not correspond to a valid file system path. It might be 475 /// remapped, or might be an artificial path such as `"<macro expansion>"`. 476 #[cfg(span_locations)] 477 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] file(&self) -> String478 pub fn file(&self) -> String { 479 self.inner.file() 480 } 481 482 /// The path to the source file in which this span occurs on disk. 483 /// 484 /// This is the actual path on disk. It is unaffected by path remapping. 485 /// 486 /// This path should not be embedded in the output of the macro; prefer 487 /// `file()` instead. 488 #[cfg(span_locations)] 489 #[cfg_attr(docsrs, doc(cfg(feature = "span-locations")))] local_file(&self) -> Option<PathBuf>490 pub fn local_file(&self) -> Option<PathBuf> { 491 self.inner.local_file() 492 } 493 494 /// Create a new span encompassing `self` and `other`. 495 /// 496 /// Returns `None` if `self` and `other` are from different files. 497 /// 498 /// Warning: the underlying [`proc_macro::Span::join`] method is 499 /// nightly-only. When called from within a procedural macro not using a 500 /// nightly compiler, this method will always return `None`. join(&self, other: Span) -> Option<Span>501 pub fn join(&self, other: Span) -> Option<Span> { 502 self.inner.join(other.inner).map(Span::_new) 503 } 504 505 /// Compares two spans to see if they're equal. 506 /// 507 /// This method is semver exempt and not exposed by default. 508 #[cfg(procmacro2_semver_exempt)] 509 #[cfg_attr(docsrs, doc(cfg(procmacro2_semver_exempt)))] eq(&self, other: &Span) -> bool510 pub fn eq(&self, other: &Span) -> bool { 511 self.inner.eq(&other.inner) 512 } 513 514 /// Returns the source text behind a span. This preserves the original 515 /// source code, including spaces and comments. It only returns a result if 516 /// the span corresponds to real source code. 517 /// 518 /// Note: The observable result of a macro should only rely on the tokens 519 /// and not on this source text. The result of this function is a best 520 /// effort to be used for diagnostics only. source_text(&self) -> Option<String>521 pub fn source_text(&self) -> Option<String> { 522 self.inner.source_text() 523 } 524 } 525 526 /// Prints a span in a form convenient for debugging. 527 impl Debug for Span { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 529 Debug::fmt(&self.inner, f) 530 } 531 } 532 533 /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`). 534 #[derive(Clone)] 535 pub enum TokenTree { 536 /// A token stream surrounded by bracket delimiters. 537 Group(Group), 538 /// An identifier. 539 Ident(Ident), 540 /// A single punctuation character (`+`, `,`, `$`, etc.). 541 Punct(Punct), 542 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc. 543 Literal(Literal), 544 } 545 546 impl TokenTree { 547 /// Returns the span of this tree, delegating to the `span` method of 548 /// the contained token or a delimited stream. span(&self) -> Span549 pub fn span(&self) -> Span { 550 match self { 551 TokenTree::Group(t) => t.span(), 552 TokenTree::Ident(t) => t.span(), 553 TokenTree::Punct(t) => t.span(), 554 TokenTree::Literal(t) => t.span(), 555 } 556 } 557 558 /// Configures the span for *only this token*. 559 /// 560 /// Note that if this token is a `Group` then this method will not configure 561 /// the span of each of the internal tokens, this will simply delegate to 562 /// the `set_span` method of each variant. set_span(&mut self, span: Span)563 pub fn set_span(&mut self, span: Span) { 564 match self { 565 TokenTree::Group(t) => t.set_span(span), 566 TokenTree::Ident(t) => t.set_span(span), 567 TokenTree::Punct(t) => t.set_span(span), 568 TokenTree::Literal(t) => t.set_span(span), 569 } 570 } 571 } 572 573 impl From<Group> for TokenTree { from(g: Group) -> Self574 fn from(g: Group) -> Self { 575 TokenTree::Group(g) 576 } 577 } 578 579 impl From<Ident> for TokenTree { from(g: Ident) -> Self580 fn from(g: Ident) -> Self { 581 TokenTree::Ident(g) 582 } 583 } 584 585 impl From<Punct> for TokenTree { from(g: Punct) -> Self586 fn from(g: Punct) -> Self { 587 TokenTree::Punct(g) 588 } 589 } 590 591 impl From<Literal> for TokenTree { from(g: Literal) -> Self592 fn from(g: Literal) -> Self { 593 TokenTree::Literal(g) 594 } 595 } 596 597 /// Prints the token tree as a string that is supposed to be losslessly 598 /// convertible back into the same token tree (modulo spans), except for 599 /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative 600 /// numeric literals. 601 impl Display for TokenTree { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 603 match self { 604 TokenTree::Group(t) => Display::fmt(t, f), 605 TokenTree::Ident(t) => Display::fmt(t, f), 606 TokenTree::Punct(t) => Display::fmt(t, f), 607 TokenTree::Literal(t) => Display::fmt(t, f), 608 } 609 } 610 } 611 612 /// Prints token tree in a form convenient for debugging. 613 impl Debug for TokenTree { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result614 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 615 // Each of these has the name in the struct type in the derived debug, 616 // so don't bother with an extra layer of indirection 617 match self { 618 TokenTree::Group(t) => Debug::fmt(t, f), 619 TokenTree::Ident(t) => { 620 let mut debug = f.debug_struct("Ident"); 621 debug.field("sym", &format_args!("{}", t)); 622 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner); 623 debug.finish() 624 } 625 TokenTree::Punct(t) => Debug::fmt(t, f), 626 TokenTree::Literal(t) => Debug::fmt(t, f), 627 } 628 } 629 } 630 631 /// A delimited token stream. 632 /// 633 /// A `Group` internally contains a `TokenStream` which is surrounded by 634 /// `Delimiter`s. 635 #[derive(Clone)] 636 pub struct Group { 637 inner: imp::Group, 638 } 639 640 /// Describes how a sequence of token trees is delimited. 641 #[derive(Copy, Clone, Debug, Eq, PartialEq)] 642 pub enum Delimiter { 643 /// `( ... )` 644 Parenthesis, 645 /// `{ ... }` 646 Brace, 647 /// `[ ... ]` 648 Bracket, 649 /// `∅ ... ∅` 650 /// 651 /// An invisible delimiter, that may, for example, appear around tokens 652 /// coming from a "macro variable" `$var`. It is important to preserve 653 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`. 654 /// Invisible delimiters may not survive roundtrip of a token stream through 655 /// a string. 656 /// 657 /// <div class="warning"> 658 /// 659 /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output 660 /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input 661 /// of a proc_macro macro are preserved, and only in very specific circumstances. 662 /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve 663 /// operator priorities as indicated above. The other `Delimiter` variants should be used 664 /// instead in this context. This is a rustc bug. For details, see 665 /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062). 666 /// 667 /// </div> 668 None, 669 } 670 671 impl Group { _new(inner: imp::Group) -> Self672 fn _new(inner: imp::Group) -> Self { 673 Group { inner } 674 } 675 _new_fallback(inner: fallback::Group) -> Self676 fn _new_fallback(inner: fallback::Group) -> Self { 677 Group { 678 inner: imp::Group::from(inner), 679 } 680 } 681 682 /// Creates a new `Group` with the given delimiter and token stream. 683 /// 684 /// This constructor will set the span for this group to 685 /// `Span::call_site()`. To change the span you can use the `set_span` 686 /// method below. new(delimiter: Delimiter, stream: TokenStream) -> Self687 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { 688 Group { 689 inner: imp::Group::new(delimiter, stream.inner), 690 } 691 } 692 693 /// Returns the punctuation used as the delimiter for this group: a set of 694 /// parentheses, square brackets, or curly braces. delimiter(&self) -> Delimiter695 pub fn delimiter(&self) -> Delimiter { 696 self.inner.delimiter() 697 } 698 699 /// Returns the `TokenStream` of tokens that are delimited in this `Group`. 700 /// 701 /// Note that the returned token stream does not include the delimiter 702 /// returned above. stream(&self) -> TokenStream703 pub fn stream(&self) -> TokenStream { 704 TokenStream::_new(self.inner.stream()) 705 } 706 707 /// Returns the span for the delimiters of this token stream, spanning the 708 /// entire `Group`. 709 /// 710 /// ```text 711 /// pub fn span(&self) -> Span { 712 /// ^^^^^^^ 713 /// ``` span(&self) -> Span714 pub fn span(&self) -> Span { 715 Span::_new(self.inner.span()) 716 } 717 718 /// Returns the span pointing to the opening delimiter of this group. 719 /// 720 /// ```text 721 /// pub fn span_open(&self) -> Span { 722 /// ^ 723 /// ``` span_open(&self) -> Span724 pub fn span_open(&self) -> Span { 725 Span::_new(self.inner.span_open()) 726 } 727 728 /// Returns the span pointing to the closing delimiter of this group. 729 /// 730 /// ```text 731 /// pub fn span_close(&self) -> Span { 732 /// ^ 733 /// ``` span_close(&self) -> Span734 pub fn span_close(&self) -> Span { 735 Span::_new(self.inner.span_close()) 736 } 737 738 /// Returns an object that holds this group's `span_open()` and 739 /// `span_close()` together (in a more compact representation than holding 740 /// those 2 spans individually). delim_span(&self) -> DelimSpan741 pub fn delim_span(&self) -> DelimSpan { 742 DelimSpan::new(&self.inner) 743 } 744 745 /// Configures the span for this `Group`'s delimiters, but not its internal 746 /// tokens. 747 /// 748 /// This method will **not** set the span of all the internal tokens spanned 749 /// by this group, but rather it will only set the span of the delimiter 750 /// tokens at the level of the `Group`. set_span(&mut self, span: Span)751 pub fn set_span(&mut self, span: Span) { 752 self.inner.set_span(span.inner); 753 } 754 } 755 756 /// Prints the group as a string that should be losslessly convertible back 757 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s 758 /// with `Delimiter::None` delimiters. 759 impl Display for Group { fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result760 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 761 Display::fmt(&self.inner, formatter) 762 } 763 } 764 765 impl Debug for Group { fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result766 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 767 Debug::fmt(&self.inner, formatter) 768 } 769 } 770 771 /// A `Punct` is a single punctuation character like `+`, `-` or `#`. 772 /// 773 /// Multicharacter operators like `+=` are represented as two instances of 774 /// `Punct` with different forms of `Spacing` returned. 775 #[derive(Clone)] 776 pub struct Punct { 777 ch: char, 778 spacing: Spacing, 779 span: Span, 780 } 781 782 /// Whether a `Punct` is followed immediately by another `Punct` or followed by 783 /// another token or whitespace. 784 #[derive(Copy, Clone, Debug, Eq, PartialEq)] 785 pub enum Spacing { 786 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`. 787 Alone, 788 /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`. 789 /// 790 /// Additionally, single quote `'` can join with identifiers to form 791 /// lifetimes `'ident`. 792 Joint, 793 } 794 795 impl Punct { 796 /// Creates a new `Punct` from the given character and spacing. 797 /// 798 /// The `ch` argument must be a valid punctuation character permitted by the 799 /// language, otherwise the function will panic. 800 /// 801 /// The returned `Punct` will have the default span of `Span::call_site()` 802 /// which can be further configured with the `set_span` method below. new(ch: char, spacing: Spacing) -> Self803 pub fn new(ch: char, spacing: Spacing) -> Self { 804 if let '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' 805 | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch 806 { 807 Punct { 808 ch, 809 spacing, 810 span: Span::call_site(), 811 } 812 } else { 813 panic!("unsupported proc macro punctuation character {:?}", ch); 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/2.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: ProcMacroAutoTraits, 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 _new_fallback(inner: fallback::Ident) -> Self938 fn _new_fallback(inner: fallback::Ident) -> Self { 939 Ident { 940 inner: imp::Ident::from(inner), 941 _marker: MARKER, 942 } 943 } 944 945 /// Creates a new `Ident` with the given `string` as well as the specified 946 /// `span`. 947 /// 948 /// The `string` argument must be a valid identifier permitted by the 949 /// language, otherwise the function will panic. 950 /// 951 /// Note that `span`, currently in rustc, configures the hygiene information 952 /// for this identifier. 953 /// 954 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" 955 /// hygiene meaning that identifiers created with this span will be resolved 956 /// as if they were written directly at the location of the macro call, and 957 /// other code at the macro call site will be able to refer to them as well. 958 /// 959 /// Later spans like `Span::def_site()` will allow to opt-in to 960 /// "definition-site" hygiene meaning that identifiers created with this 961 /// span will be resolved at the location of the macro definition and other 962 /// code at the macro call site will not be able to refer to them. 963 /// 964 /// Due to the current importance of hygiene this constructor, unlike other 965 /// tokens, requires a `Span` to be specified at construction. 966 /// 967 /// # Panics 968 /// 969 /// Panics if the input string is neither a keyword nor a legal variable 970 /// name. If you are not sure whether the string contains an identifier and 971 /// need to handle an error case, use 972 /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code 973 /// style="padding-right:0;">syn::parse_str</code></a><code 974 /// style="padding-left:0;">::<Ident></code> 975 /// rather than `Ident::new`. 976 #[track_caller] new(string: &str, span: Span) -> Self977 pub fn new(string: &str, span: Span) -> Self { 978 Ident::_new(imp::Ident::new_checked(string, span.inner)) 979 } 980 981 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The 982 /// `string` argument must be a valid identifier permitted by the language 983 /// (including keywords, e.g. `fn`). Keywords which are usable in path 984 /// segments (e.g. `self`, `super`) are not supported, and will cause a 985 /// panic. 986 #[track_caller] new_raw(string: &str, span: Span) -> Self987 pub fn new_raw(string: &str, span: Span) -> Self { 988 Ident::_new(imp::Ident::new_raw_checked(string, span.inner)) 989 } 990 991 /// Returns the span of this `Ident`. span(&self) -> Span992 pub fn span(&self) -> Span { 993 Span::_new(self.inner.span()) 994 } 995 996 /// Configures the span of this `Ident`, possibly changing its hygiene 997 /// context. set_span(&mut self, span: Span)998 pub fn set_span(&mut self, span: Span) { 999 self.inner.set_span(span.inner); 1000 } 1001 } 1002 1003 impl PartialEq for Ident { eq(&self, other: &Ident) -> bool1004 fn eq(&self, other: &Ident) -> bool { 1005 self.inner == other.inner 1006 } 1007 } 1008 1009 impl<T> PartialEq<T> for Ident 1010 where 1011 T: ?Sized + AsRef<str>, 1012 { eq(&self, other: &T) -> bool1013 fn eq(&self, other: &T) -> bool { 1014 self.inner == other 1015 } 1016 } 1017 1018 impl Eq for Ident {} 1019 1020 impl PartialOrd for Ident { partial_cmp(&self, other: &Ident) -> Option<Ordering>1021 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> { 1022 Some(self.cmp(other)) 1023 } 1024 } 1025 1026 impl Ord for Ident { cmp(&self, other: &Ident) -> Ordering1027 fn cmp(&self, other: &Ident) -> Ordering { 1028 self.to_string().cmp(&other.to_string()) 1029 } 1030 } 1031 1032 impl Hash for Ident { hash<H: Hasher>(&self, hasher: &mut H)1033 fn hash<H: Hasher>(&self, hasher: &mut H) { 1034 self.to_string().hash(hasher); 1035 } 1036 } 1037 1038 /// Prints the identifier as a string that should be losslessly convertible back 1039 /// into the same identifier. 1040 impl Display for Ident { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1041 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1042 Display::fmt(&self.inner, f) 1043 } 1044 } 1045 1046 impl Debug for Ident { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1047 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1048 Debug::fmt(&self.inner, f) 1049 } 1050 } 1051 1052 /// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`), 1053 /// byte character (`b'a'`), an integer or floating point number with or without 1054 /// a suffix (`1`, `1u8`, `2.3`, `2.3f32`). 1055 /// 1056 /// Boolean literals like `true` and `false` do not belong here, they are 1057 /// `Ident`s. 1058 #[derive(Clone)] 1059 pub struct Literal { 1060 inner: imp::Literal, 1061 _marker: ProcMacroAutoTraits, 1062 } 1063 1064 macro_rules! suffixed_int_literals { 1065 ($($name:ident => $kind:ident,)*) => ($( 1066 /// Creates a new suffixed integer literal with the specified value. 1067 /// 1068 /// This function will create an integer like `1u32` where the integer 1069 /// value specified is the first part of the token and the integral is 1070 /// also suffixed at the end. Literals created from negative numbers may 1071 /// not survive roundtrips through `TokenStream` or strings and may be 1072 /// broken into two tokens (`-` and positive literal). 1073 /// 1074 /// Literals created through this method have the `Span::call_site()` 1075 /// span by default, which can be configured with the `set_span` method 1076 /// below. 1077 pub fn $name(n: $kind) -> Literal { 1078 Literal::_new(imp::Literal::$name(n)) 1079 } 1080 )*) 1081 } 1082 1083 macro_rules! unsuffixed_int_literals { 1084 ($($name:ident => $kind:ident,)*) => ($( 1085 /// Creates a new unsuffixed integer literal with the specified value. 1086 /// 1087 /// This function will create an integer like `1` where the integer 1088 /// value specified is the first part of the token. No suffix is 1089 /// specified on this token, meaning that invocations like 1090 /// `Literal::i8_unsuffixed(1)` are equivalent to 1091 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers 1092 /// may not survive roundtrips through `TokenStream` or strings and may 1093 /// be broken into two tokens (`-` and positive literal). 1094 /// 1095 /// Literals created through this method have the `Span::call_site()` 1096 /// span by default, which can be configured with the `set_span` method 1097 /// below. 1098 pub fn $name(n: $kind) -> Literal { 1099 Literal::_new(imp::Literal::$name(n)) 1100 } 1101 )*) 1102 } 1103 1104 impl Literal { _new(inner: imp::Literal) -> Self1105 fn _new(inner: imp::Literal) -> Self { 1106 Literal { 1107 inner, 1108 _marker: MARKER, 1109 } 1110 } 1111 _new_fallback(inner: fallback::Literal) -> Self1112 fn _new_fallback(inner: fallback::Literal) -> Self { 1113 Literal { 1114 inner: imp::Literal::from(inner), 1115 _marker: MARKER, 1116 } 1117 } 1118 1119 suffixed_int_literals! { 1120 u8_suffixed => u8, 1121 u16_suffixed => u16, 1122 u32_suffixed => u32, 1123 u64_suffixed => u64, 1124 u128_suffixed => u128, 1125 usize_suffixed => usize, 1126 i8_suffixed => i8, 1127 i16_suffixed => i16, 1128 i32_suffixed => i32, 1129 i64_suffixed => i64, 1130 i128_suffixed => i128, 1131 isize_suffixed => isize, 1132 } 1133 1134 unsuffixed_int_literals! { 1135 u8_unsuffixed => u8, 1136 u16_unsuffixed => u16, 1137 u32_unsuffixed => u32, 1138 u64_unsuffixed => u64, 1139 u128_unsuffixed => u128, 1140 usize_unsuffixed => usize, 1141 i8_unsuffixed => i8, 1142 i16_unsuffixed => i16, 1143 i32_unsuffixed => i32, 1144 i64_unsuffixed => i64, 1145 i128_unsuffixed => i128, 1146 isize_unsuffixed => isize, 1147 } 1148 1149 /// Creates a new unsuffixed floating-point literal. 1150 /// 1151 /// This constructor is similar to those like `Literal::i8_unsuffixed` where 1152 /// the float's value is emitted directly into the token but no suffix is 1153 /// used, so it may be inferred to be a `f64` later in the compiler. 1154 /// Literals created from negative numbers may not survive round-trips 1155 /// through `TokenStream` or strings and may be broken into two tokens (`-` 1156 /// and positive literal). 1157 /// 1158 /// # Panics 1159 /// 1160 /// This function requires that the specified float is finite, for example 1161 /// if it is infinity or NaN this function will panic. f64_unsuffixed(f: f64) -> Literal1162 pub fn f64_unsuffixed(f: f64) -> Literal { 1163 assert!(f.is_finite()); 1164 Literal::_new(imp::Literal::f64_unsuffixed(f)) 1165 } 1166 1167 /// Creates a new suffixed floating-point literal. 1168 /// 1169 /// This constructor will create a literal like `1.0f64` where the value 1170 /// specified is the preceding part of the token and `f64` is the suffix of 1171 /// the token. This token will always be inferred to be an `f64` in the 1172 /// compiler. Literals created from negative numbers may not survive 1173 /// round-trips through `TokenStream` or strings and may be broken into two 1174 /// tokens (`-` and positive literal). 1175 /// 1176 /// # Panics 1177 /// 1178 /// This function requires that the specified float is finite, for example 1179 /// if it is infinity or NaN this function will panic. f64_suffixed(f: f64) -> Literal1180 pub fn f64_suffixed(f: f64) -> Literal { 1181 assert!(f.is_finite()); 1182 Literal::_new(imp::Literal::f64_suffixed(f)) 1183 } 1184 1185 /// Creates a new unsuffixed floating-point literal. 1186 /// 1187 /// This constructor is similar to those like `Literal::i8_unsuffixed` where 1188 /// the float's value is emitted directly into the token but no suffix is 1189 /// used, so it may be inferred to be a `f64` later in the compiler. 1190 /// Literals created from negative numbers may not survive round-trips 1191 /// through `TokenStream` or strings and may be broken into two tokens (`-` 1192 /// and positive literal). 1193 /// 1194 /// # Panics 1195 /// 1196 /// This function requires that the specified float is finite, for example 1197 /// if it is infinity or NaN this function will panic. f32_unsuffixed(f: f32) -> Literal1198 pub fn f32_unsuffixed(f: f32) -> Literal { 1199 assert!(f.is_finite()); 1200 Literal::_new(imp::Literal::f32_unsuffixed(f)) 1201 } 1202 1203 /// Creates a new suffixed floating-point literal. 1204 /// 1205 /// This constructor will create a literal like `1.0f32` where the value 1206 /// specified is the preceding part of the token and `f32` is the suffix of 1207 /// the token. This token will always be inferred to be an `f32` in the 1208 /// compiler. Literals created from negative numbers may not survive 1209 /// round-trips through `TokenStream` or strings and may be broken into two 1210 /// tokens (`-` and positive literal). 1211 /// 1212 /// # Panics 1213 /// 1214 /// This function requires that the specified float is finite, for example 1215 /// if it is infinity or NaN this function will panic. f32_suffixed(f: f32) -> Literal1216 pub fn f32_suffixed(f: f32) -> Literal { 1217 assert!(f.is_finite()); 1218 Literal::_new(imp::Literal::f32_suffixed(f)) 1219 } 1220 1221 /// String literal. string(string: &str) -> Literal1222 pub fn string(string: &str) -> Literal { 1223 Literal::_new(imp::Literal::string(string)) 1224 } 1225 1226 /// Character literal. character(ch: char) -> Literal1227 pub fn character(ch: char) -> Literal { 1228 Literal::_new(imp::Literal::character(ch)) 1229 } 1230 1231 /// Byte character literal. byte_character(byte: u8) -> Literal1232 pub fn byte_character(byte: u8) -> Literal { 1233 Literal::_new(imp::Literal::byte_character(byte)) 1234 } 1235 1236 /// Byte string literal. byte_string(bytes: &[u8]) -> Literal1237 pub fn byte_string(bytes: &[u8]) -> Literal { 1238 Literal::_new(imp::Literal::byte_string(bytes)) 1239 } 1240 1241 /// C string literal. c_string(string: &CStr) -> Literal1242 pub fn c_string(string: &CStr) -> Literal { 1243 Literal::_new(imp::Literal::c_string(string)) 1244 } 1245 1246 /// Returns the span encompassing this literal. span(&self) -> Span1247 pub fn span(&self) -> Span { 1248 Span::_new(self.inner.span()) 1249 } 1250 1251 /// Configures the span associated for this literal. set_span(&mut self, span: Span)1252 pub fn set_span(&mut self, span: Span) { 1253 self.inner.set_span(span.inner); 1254 } 1255 1256 /// Returns a `Span` that is a subset of `self.span()` containing only 1257 /// the source bytes in range `range`. Returns `None` if the would-be 1258 /// trimmed span is outside the bounds of `self`. 1259 /// 1260 /// Warning: the underlying [`proc_macro::Literal::subspan`] method is 1261 /// nightly-only. When called from within a procedural macro not using a 1262 /// nightly compiler, this method will always return `None`. subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span>1263 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> { 1264 self.inner.subspan(range).map(Span::_new) 1265 } 1266 1267 // Intended for the `quote!` macro to use when constructing a proc-macro2 1268 // token out of a macro_rules $:literal token, which is already known to be 1269 // a valid literal. This avoids reparsing/validating the literal's string 1270 // representation. This is not public API other than for quote. 1271 #[doc(hidden)] from_str_unchecked(repr: &str) -> Self1272 pub unsafe fn from_str_unchecked(repr: &str) -> Self { 1273 Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) }) 1274 } 1275 } 1276 1277 impl FromStr for Literal { 1278 type Err = LexError; 1279 from_str(repr: &str) -> Result<Self, LexError>1280 fn from_str(repr: &str) -> Result<Self, LexError> { 1281 match imp::Literal::from_str_checked(repr) { 1282 Ok(lit) => Ok(Literal::_new(lit)), 1283 Err(lex) => Err(LexError { 1284 inner: lex, 1285 _marker: MARKER, 1286 }), 1287 } 1288 } 1289 } 1290 1291 impl Debug for Literal { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1292 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1293 Debug::fmt(&self.inner, f) 1294 } 1295 } 1296 1297 impl Display for Literal { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1299 Display::fmt(&self.inner, f) 1300 } 1301 } 1302 1303 /// Public implementation details for the `TokenStream` type, such as iterators. 1304 pub mod token_stream { 1305 use crate::marker::{ProcMacroAutoTraits, MARKER}; 1306 use crate::{imp, TokenTree}; 1307 use core::fmt::{self, Debug}; 1308 1309 pub use crate::TokenStream; 1310 1311 /// An iterator over `TokenStream`'s `TokenTree`s. 1312 /// 1313 /// The iteration is "shallow", e.g. the iterator doesn't recurse into 1314 /// delimited groups, and returns whole groups as token trees. 1315 #[derive(Clone)] 1316 pub struct IntoIter { 1317 inner: imp::TokenTreeIter, 1318 _marker: ProcMacroAutoTraits, 1319 } 1320 1321 impl Iterator for IntoIter { 1322 type Item = TokenTree; 1323 next(&mut self) -> Option<TokenTree>1324 fn next(&mut self) -> Option<TokenTree> { 1325 self.inner.next() 1326 } 1327 size_hint(&self) -> (usize, Option<usize>)1328 fn size_hint(&self) -> (usize, Option<usize>) { 1329 self.inner.size_hint() 1330 } 1331 } 1332 1333 impl Debug for IntoIter { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result1334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1335 f.write_str("TokenStream ")?; 1336 f.debug_list().entries(self.clone()).finish() 1337 } 1338 } 1339 1340 impl IntoIterator for TokenStream { 1341 type Item = TokenTree; 1342 type IntoIter = IntoIter; 1343 into_iter(self) -> IntoIter1344 fn into_iter(self) -> IntoIter { 1345 IntoIter { 1346 inner: self.inner.into_iter(), 1347 _marker: MARKER, 1348 } 1349 } 1350 } 1351 } 1352