lib.rs 44 KB

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