proc-macro-utils-0.10.0/.cargo_vcs_info.json0000644000000001360000000000100143120ustar { "git": { "sha1": "a6995bb9ff248b55fcefd1f6842f72676f5dbcf8" }, "path_in_vcs": "" }proc-macro-utils-0.10.0/CHANGELOG.md000064400000000000000000000073661046102023000147270ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.10.0] - 2024-05-21 ### Changed - `next_expression()` stops at `=>` as well, matching `macro_rule`'s `expr` ## [0.9.1] - 2024-03-13 ### Added - `span()` to `TokenParser`. ## [0.9.0] - 2024-03-13 ### Added - `*_tt` functions to `TokenParser`. - `next_macro_rules_tt()` to `TokenParser`. - `TokenTreeLiteral` with `is_string()` and `string()`. ### Changed - **Breaking Change** Sealed extension traits. ### Fixed - `assert_expansion!` was failing on nightly. ## [0.8.0] - 2023-05-14 ### Fixed - bumped `smallvec` version to `1.5` to avoid nightly feature compilation issues. ## [0.7.0] - 2023-05-14 - Increased documentation and test coverage. ### Added - `quote::ToTokens` implementation for `TokenParser` (`quote` is a new default feature). - `peek_{token}` and `peek_n_{token}` to `TokenParser`. - `alone` to `TokenTreePunct` ensuring if a token is `Punct` its `spacing` is `Alone` - `*_alone` functions to `TokenParser` setting the last token to `Alone` if it is a punctuation. - `next_n` to `TokenParser` returning the next `n` tokens. - `peek_range` to `TokenParser` returning a range of tokens. - `FromStr` implementation for `TokenParser` based on `TokenStream`'s. - `assert_expansion!` macro to unit test macro implementations. ### Changed - **Breaking Change** Added const generic buffer size to `TokenParser`. - **Breaking Change** `Peeker::peek` takes `&[TokenTree]` instead of `TokenParser`. - **Breaking Change** `Peeker::LENGTH` is function `len` now. - **Breaking Change** `*_{delimiter}` returns `Group` instead of the contained stream. To get to the stream call `.stream()` - **Breaking Change** `TokenParser::*_{punctuation}` got renamed to `*_tt_{punctuation}` and their behaviour was changed to match that of `$tt` in macro_rules instead of requiring `Spacing::Alone`, returned `spacing` is set to `Alone`. - `TokenParser` peeking supports `n` greater than stack buffer, allowing spilling to heap. - Increased default `TokenParser` peek buffer to `6`. - Marked parser functions as must_use. - `next_expr` and `next_type` set the last tokens `spacing` to `Alone`. ### Fixed - Allow `assert_tokens` in expression position e.g. unbraced `match` arm ## [0.6.0] - 2023-04-29 - `TokenParser::next_keyword(v)` ## [0.5.2] - 2023-04-06 ### Fixed - `TokenParser::peek_n()` always returned `None` - `TokenParser::next_{token}` did not work correctly because of `peek_n` ## [0.5.1] - 2023-03-02 ### Fixed - `TokenParser::next_string()` did not consume token ## [0.5.0] - 2023-03-01 ### Added - `TokenParser` for parsing simple rust structures - `assert_tokens!` macro - `TokenTreeExt::into_()` functions - `Delimited` trait for accessing `TokenTree::Group` ### Changed - **Breaking Change** `TokenTreeExt::()` now return references [unreleased]: https://github.com/ModProg/proc-macro-utils/compare/v0.10.0...HEAD [0.10.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.9.1...v0.10.0 [0.9.1]: https://github.com/ModProg/proc-macro-utils/compare/v0.9.0...v0.9.1 [0.9.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.8.0...v0.9.0 [0.8.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.7.0...v0.8.0 [0.7.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.5.2...v0.6.0 [0.5.2]: https://github.com/ModProg/proc-macro-utils/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/ModProg/proc-macro-utils/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/ModProg/proc-macro-utils/compare/v0.4.0...v0.5.0 proc-macro-utils-0.10.0/Cargo.toml0000644000000034300000000000100123100ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "proc-macro-utils" version = "0.10.0" include = [ "src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md", ] description = "low-level utilities on proc-macro and proc-macro2 types" documentation = "https://docs.rs/proc-macro-utils" readme = "README.md" keywords = ["macros"] categories = ["development-tools::procedural-macro-helpers"] license = "MIT OR Apache-2.0" repository = "https://github.com/ModProg/proc-macro-utils" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = """ ## [{{version}}] - {{date}}""" search = '## \[Unreleased\]' [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = """ [unreleased]: $1/{{tag_name}}...HEAD [{{version}}]: $1/$2...{{tag_name}}""" search = '\[unreleased\]: (.*)/(v.*)\.\.\.HEAD' [dependencies.proc-macro2] version = "1" optional = true [dependencies.quote] version = "1" optional = true [dependencies.smallvec] version = "1.5" features = ["const_generics"] optional = true [dev-dependencies.quote] version = "1" [features] default = [ "proc-macro2", "proc-macro", "parser", "quote", ] parser = [ "smallvec", "proc-macro2", ] proc-macro = [] proc-macro-utils-0.10.0/Cargo.toml.orig000064400000000000000000000027461046102023000160020ustar 00000000000000[package] name = "proc-macro-utils" version = "0.10.0" edition = "2021" categories = ["development-tools::procedural-macro-helpers"] description = "low-level utilities on proc-macro and proc-macro2 types" keywords = ["macros"] license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/ModProg/proc-macro-utils" documentation = "https://docs.rs/proc-macro-utils" include = ["src/**/*", "LICENSE-*", "README.md", "CHANGELOG.md"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] proc-macro2 = { version = "1", optional = true } quote = { version = "1", optional = true } smallvec = { version = "1.5", optional = true, features = ["const_generics"] } [features] default = ["proc-macro2", "proc-macro", "parser", "quote"] proc-macro = [] parser = ["smallvec", "proc-macro2"] [dev-dependencies] quote = "1" [workspace] members = ["example"] # docs.rs-specific configuration [package.metadata.docs.rs] # document all features all-features = true # defines the configuration attribute `docsrs` rustdoc-args = ["--cfg", "docsrs"] [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = '## \[Unreleased\]' replace = """ ## [{{version}}] - {{date}}\ """ [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" search = '\[unreleased\]: (.*)/(v.*)\.\.\.HEAD' replace = """ [unreleased]: $1/{{tag_name}}...HEAD [{{version}}]: $1/$2...{{tag_name}}\ """ proc-macro-utils-0.10.0/LICENSE-APACHE000064400000000000000000000261351046102023000150350ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a peretual, worldwide, non-exclusive, no-cpharge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides it s Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. proc-macro-utils-0.10.0/LICENSE-MIT000064400000000000000000000020631046102023000145370ustar 00000000000000MIT License Copyright (c) 2023 Roland Fredenhagen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. proc-macro-utils-0.10.0/README.md000064400000000000000000000011561046102023000143640ustar 00000000000000# proc-macro-utils [![CI Status](https://github.com/ModProg/proc-macro-utils/actions/workflows/test.yaml/badge.svg)](https://github.com/ModProg/proc-macro-utils/actions/workflows/test.yaml) [![Crates.io](https://img.shields.io/crates/v/proc-macro-utils)](https://crates.io/crates/proc-macro-utils) [![Docs.rs](https://img.shields.io/crates/v/proc-macro-utils?color=informational&label=docs.rs)](https://docs.rs/proc-macro-utils) [![Documentation for `main`](https://img.shields.io/badge/docs-main-informational)](https://modprog.github.io/proc-macro-utils/proc_macro_utils/) Some utility functions on proc-macro types. proc-macro-utils-0.10.0/src/__private.rs000064400000000000000000000002701046102023000162060ustar 00000000000000pub use proc_macro2; use proc_macro2::TokenTree; #[allow(non_snake_case)] #[inline(always)] pub fn assert_impl_IntoIterator_Item_TokenTree(_: &impl IntoIterator) {} proc-macro-utils-0.10.0/src/assert.rs000064400000000000000000000237211046102023000155450ustar 00000000000000/// Allows simple unit testing of proc macro implementations. /// /// This macro only works with functions taking [`proc_macro2::TokenStream`] due /// to the [`proc_macro`] API not being available in unit tests. This can be /// achieved either by manually creating a separate function: /// ```ignore /// use proc_macro::TokenStream; /// use proc_macro2::TokenStream as TokenStream2; /// #[proc_macro] /// pub fn actual_macro(input: TokenStream) -> TokenStream { /// macro_impl(input.into()).into() /// } /// fn macro_impl(input: TokenStream2) -> TokenStream2 { /// // ... /// } /// ``` /// or use a crate like [`manyhow`](https://docs.rs/manyhow/): /// ```ignore /// use proc_macro2::TokenStream as TokenStream2; /// #[manyhow(impl_fn)] // generates `fn actual_macro_impl` /// pub fn actual_macro(input: TokenStream2) -> TokenStream2 { /// // ... /// } /// ``` /// /// # Function like macros /// ``` /// # use proc_macro_utils::assert_expansion; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// // Dummy attribute macro impl /// fn macro_impl(input: TokenStream) -> TokenStream { /// quote!(#input) /// } /// fn macro_impl_result(input: TokenStream) -> Result { /// Ok(quote!(#input)) /// } /// assert_expansion!( /// macro_impl!(something test), /// { something test } /// ); /// assert_expansion!( /// macro_impl![1, 2, 3], /// { 1, 2, 3 } /// ); /// assert_expansion!( /// macro_impl!{ braced }, /// { braced } /// ); /// // adding a single function call (without arguments) is also allowed e.g. `unwrap()` /// assert_expansion!( /// macro_impl_result!(result).unwrap(), /// { result } /// ); /// ``` /// /// # Derive macros /// ``` /// # use proc_macro_utils::assert_expansion; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// // Dummy derive macro impl /// fn macro_impl(item: TokenStream) -> TokenStream { /// quote!(#item) /// } /// fn macro_impl_result(item: TokenStream) -> Result { /// Ok(quote!(#item)) /// } /// assert_expansion!( /// #[derive(macro_impl)] /// struct A; // the comma after items is optional /// { struct A; } /// ); /// assert_expansion!( /// #[derive(macro_impl)] /// struct A {} /// { struct A {} } /// ); /// // adding a single function call (without arguments) is also allowed e.g. `unwrap()` /// assert_expansion!( /// #[derive(macro_impl_result)] /// struct A {}.unwrap() /// { struct A {} } /// ); /// // alternatively the proc_macro syntax is compatible /// assert_expansion!( /// macro_impl!{ struct A {} }, /// { struct A {} } /// ); /// ``` /// /// # Attribute macros /// ``` /// # use proc_macro_utils::assert_expansion; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// // Dummy attribute macro impl /// fn macro_impl(input: TokenStream, item: TokenStream) -> TokenStream { /// quote!(#input, #item) /// } /// fn macro_impl_result(input: TokenStream, item: TokenStream) -> Result { /// Ok(quote!(#input, #item)) /// } /// assert_expansion!( /// #[macro_impl] /// struct A; /// { , struct A; } /// ); /// assert_expansion!( /// #[macro_impl = "hello"] /// fn test() { }, // the comma after items is optional /// { "hello", fn test() {} } /// ); /// assert_expansion!( /// #[macro_impl(a = 10)] /// impl Hello for World {}, /// { a = 10, impl Hello for World {} } /// ); /// // adding a single function call (without arguments) is also allowed e.g. `unwrap()` /// assert_expansion!( /// #[macro_impl_result(a = 10)] /// impl Hello for World {}.unwrap(), /// { a = 10, impl Hello for World {} } /// ); /// ``` /// /// # Generic usage /// On top of the normal macro inputs a generic input is also supported. /// ``` /// # use proc_macro_utils::assert_expansion; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// fn macro_impl(first: TokenStream, second: TokenStream, third: TokenStream) -> TokenStream { /// quote!(#first, #second, #third) /// } /// fn macro_impl_result(first: TokenStream, second: TokenStream, third: TokenStream) -> Result { /// Ok(quote!(#first, #second, #third)) /// } /// assert_expansion!( /// macro_impl({ 1 }, { something }, { ":)" }), /// { 1, something, ":)" } /// ); /// // adding a single function call (without arguments) is also allowed e.g. `unwrap()` /// assert_expansion!( /// macro_impl_result({ 1 }, { something }, { ":)" }).unwrap(), /// { 1, something, ":)" } /// ); /// ``` #[macro_export] #[allow(clippy::module_name_repetitions)] macro_rules! assert_expansion { ($macro:ident!($($input:tt)*)$(.$fn:ident())?, { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$($input)*})$(.$fn())?, { $($rhs)* }) }; ($macro:ident![$($input:tt)*]$(.$fn:ident())?, { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$($input)*})$(.$fn())?, { $($rhs)* }) }; ($macro:ident!{$($input:tt)*}$(.$fn:ident())?, { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$($input)*})$(.$fn())?, { $($rhs)* }) }; (#[derive($macro:ident)]$item:item$(.$fn:ident())?$(,)? { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$item})$(.$fn())?, { $($rhs)* }) }; (#[$macro:ident]$item:item$(.$fn:ident())?$(,)? { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({}, {$item})$(.$fn())?, { $($rhs)* }) }; (#[$macro:ident = $input:expr]$item:item$(.$fn:ident())?$(,)? { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$input}, {$item})$(.$fn())?, { $($rhs)* }) }; (#[$macro:ident($($input:tt)*)]$item:item$(.$fn:ident())?$(,)? { $($rhs:tt)* }) => { $crate::assert_expansion!($macro({$($input)*}, {$item})$(.$fn())?, { $($rhs)* }) }; ($macro:ident($({$($input:tt)*}),+$(,)?)$(.$fn:ident())?, {$($rhs:tt)*}) => { $crate::assert_tokens!( $crate::__private::proc_macro2::TokenStream::from($macro( $(<$crate::__private::proc_macro2::TokenStream as ::core::str::FromStr> ::from_str(::core::stringify!($($input)*)).unwrap().into()),+ )$(.$fn())?), { $($rhs)* } ) }; } /// Asserts that the `lhs` matches the tokens wrapped in braces on the `rhs`. /// /// `lhs` needs to be an expression implementing `IntoIterator` /// e.g. [`TokenStream`](proc_macro2::TokenStream) or /// [`TokenParser`](crate::TokenParser). /// ``` /// # use quote::quote; /// # use proc_macro_utils::assert_tokens; /// let some_tokens = quote! { ident, { group } }; /// /// assert_tokens! {some_tokens, { ident, {group} }}; /// ``` #[macro_export] #[cfg(doc)] macro_rules! assert_tokens { ($lhs:expr, { $($rhs:tt)* }) => {}; } #[macro_export] #[cfg(not(doc))] #[doc(hidden)] #[allow(clippy::module_name_repetitions)] macro_rules! assert_tokens { ($lhs:expr, {$($rhs:tt)*}) => {{ let mut lhs = $crate::TokenParser::new_generic::<3, _, _>($lhs); $crate::assert_tokens!(@O lhs, "", $($rhs)*); }}; (@E $prefix:expr, $expected:tt, $found:tt) => { panic!("expected\n {}\nfound\n {}\nat\n {} {}", stringify!$expected, $found, $prefix, $found); }; (@E $prefix:expr, $expected:tt) => { panic!("unexpected end, expected\n {}\nafter\n {}", stringify!$expected, $prefix); }; (@G $lhs:ident, $fn:ident, $aggr:expr, $sym:literal, $group:tt, {$($inner:tt)*}, $($rhs:tt)*) => { if let Some(lhs) = $lhs.$fn() { let mut lhs = $crate::TokenParser::<_, 3>::from($crate::__private::proc_macro2::Group::stream(&lhs)); $crate::assert_tokens!(@O lhs, concat!($aggr, ' ', $sym), $($inner)*); } else if let Some(lhs) = $lhs.next() { $crate::assert_tokens!(@E $aggr, ($group), lhs); } else { $crate::assert_tokens!(@E $aggr, ($group)); } $crate::assert_tokens!(@O $lhs, $crate::assert_tokens!(@C $aggr, $group), $($rhs)*); }; // These don't add a whitespace in front (@C $lhs:expr, ,) => { concat!($lhs, ',') }; (@C $lhs:expr, :) => { concat!($lhs, ':') }; (@C $lhs:expr, ;) => { concat!($lhs, ';') }; (@C $lhs:expr, .) => { concat!($lhs, '.') }; // All other tokens do (@C $lhs:expr, $rhs:tt) => { concat!($lhs, ' ', stringify!($rhs)) }; (@O $lhs:ident, $aggr:expr,) => { assert!($lhs.is_empty(), "unexpected left over tokens `{}`", $lhs.into_token_stream()); }; (@O $lhs:ident, $aggr:expr, ( $($inner:tt)* ) $($rhs:tt)*) => { $crate::assert_tokens!(@G $lhs, next_parenthesized, $aggr, '(', { $($inner)* }, { $($inner)* }, $($rhs)*); }; (@O $lhs:ident, $aggr:expr, { $($inner:tt)* } $($rhs:tt)*) => { $crate::assert_tokens!(@G $lhs, next_braced, $aggr, '{', { $($inner)* }, { $($inner)* }, $($rhs)*); }; (@O $lhs:ident, $aggr:expr, [ $($inner:tt)* ] $($rhs:tt)*) => { $crate::assert_tokens!(@G $lhs, next_bracketed, $aggr, '[', [ $($inner)* ], { $($inner)* }, $($rhs)*); }; (@O $lhs:ident, $aggr:expr, $token:tt $($rhs:tt)*) => { if let Some(lhs) = $lhs.next_macro_rules_tt().map(|t|t.to_string()).or_else(|| $lhs.next().map(|t|t.to_string())) { if(lhs != stringify!($token)) { $crate::assert_tokens!(@E $aggr, ($token), lhs); } } else { $crate::assert_tokens!(@E $aggr, ($token)); } $crate::assert_tokens!(@O $lhs, $crate::assert_tokens!(@C $aggr, $token), $($rhs)*); }; } #[test] fn test() { // TODO testing with quote is incomplete `":::"` can be joint joint alone if // produced directly not with quote. use quote::quote; assert_tokens!(quote!(ident ident, { group/test, vec![a, (a + b)] }, "literal" $), { ident ident, { group /test, vec![a,(a+b)] }, "literal" $ }); assert_tokens!(quote!(:::), { ::: }); assert_tokens!(quote!(more:::test::test:: hello :-D $$$ It should just work), { more ::: test ::test:: hello :-D $$$ It should just work }); assert_tokens!(quote!(:$), {: $}); } proc-macro-utils-0.10.0/src/lib.rs000064400000000000000000000406331046102023000150130ustar 00000000000000//! Some useful functions on [`proc_macro`] and [`proc_macro2`] types //! //! E.g. [pushing tokens onto `TokenStream`](TokenStreamExt::push) and [testing //! for specific punctuation on `TokenTree` and `Punct`](TokenTreePunct) //! //! It also adds the [`assert_tokens!`] and [`assert_expansion!`] macros to //! improve unit testability for `proc-macros`. #![warn(clippy::pedantic, missing_docs)] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![deny(rustdoc::all)] #[cfg(doc)] use proc_macro2::{Punct, Spacing}; #[cfg(feature = "proc-macro")] extern crate proc_macro; /// Parsing of simple rust structures without syn #[cfg(feature = "parser")] mod parser; #[cfg(feature = "parser")] pub use parser::TokenParser; #[cfg(feature = "parser")] #[macro_use] mod assert; #[cfg(feature = "parser")] #[doc(hidden)] pub mod __private; mod sealed { pub trait Sealed {} macro_rules! sealed { [$($ty:ident),* $(,)?] => {$( impl Sealed for proc_macro::$ty {} impl Sealed for proc_macro2::$ty {} )*}; } sealed![TokenStream, TokenTree, Punct, Literal, Group]; } macro_rules! once { (($($tts:tt)*) $($tail:tt)*) => { $($tts)* }; } macro_rules! attr { (($($attr:tt)*), $($item:tt)+) => { $(#$attr)* $($item)+ }; } macro_rules! trait_def { ($item_attr:tt, $trait:ident, $($fn_attr:tt, $fn:ident, $({$($gen:tt)*})?, $args:tt, $($ret:ty)?),*) => { attr!($item_attr, pub trait $trait: crate::sealed::Sealed { $(attr!($fn_attr, fn $fn $($($gen)*)? $args $(-> $ret)?;);)* }); }; } macro_rules! trait_impl { ($trait:ident, $type:ident, $($fn_attr:tt, $fn:ident, $({$($gen:tt)*})?, $args:tt, $($ret:ty)?, $stmts:tt),*) => { impl $trait for $type { $(attr!($fn_attr, fn $fn $($($gen)*)? $args $(-> $ret)? $stmts);)* } }; } macro_rules! impl_via_trait { ($( $(#$trait_attr:tt)* impl $trait:ident for $type:ident { $($(#$fn_attr:tt)* fn $fn:ident $({$($gen:tt)*})? ($($args:tt)*) $(-> $ret:ty)? { $($stmts:tt)* })* } )+) => { once!($((trait_def!(($($trait_attr)*), $trait, $(($($fn_attr)*), $fn,$({$($gen)*})?, ($($args)*), $($ret)?),*);))+); #[cfg(feature = "proc-macro")] const _: () = { use proc_macro::*; $(trait_impl!($trait, $type, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?, {$($stmts)*}),*);)+ }; #[cfg(feature = "proc-macro2")] const _:() = { use proc_macro2::*; $(trait_impl!($trait, $type, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?, {$($stmts)*}),*);)+ }; }; ( mod $mod:ident, $mod2:ident { $( $(#$trait_attr:tt)* impl $trait:ident$($doc:literal)?, $trait2:ident$($doc2:literal)? for $type:ident { $($(#$fn_attr:tt)* fn $fn:ident $({$($gen:tt)*})? ($($args:tt)*) $(-> $ret:ty)? { $($stmts:tt)* })* } )+ } ) => { #[cfg(feature = "proc-macro")] once!(($(pub use $mod::$trait;)+)); #[cfg(feature = "proc-macro")] mod $mod { use proc_macro::*; once!($((trait_def!(($($trait_attr)* $([doc=$doc])?), $trait, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?),*);))+); $(trait_impl!($trait, $type, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?, {$($stmts)*}),*);)+ } #[cfg(feature = "proc-macro2")] once!(($(pub use $mod2::$trait2;)+)); #[cfg(feature = "proc-macro2")] mod $mod2 { use proc_macro2::*; once!($((trait_def!(($($trait_attr)*$([doc=$doc2])?), $trait2, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?),*);))+); $(trait_impl!($trait2, $type, $(($($fn_attr)*), $fn, $({$($gen)*})?, ($($args)*), $($ret)?, {$($stmts)*}),*);)+ } }; } impl_via_trait! { mod token_stream_ext, token_stream2_ext { /// Generic extensions for impl TokenStreamExt "[`proc_macro::TokenStream`]", TokenStream2Ext "[`proc_macro2::TokenStream`]" for TokenStream { /// Pushes a single [`TokenTree`] onto the token stream. fn push(&mut self, token: TokenTree) { self.extend(std::iter::once(token)) } /// Creates a [`TokenParser`](crate::TokenParser) from this token stream. #[cfg(feature = "parser")] fn parser(self) -> crate::TokenParser { #[allow(clippy::useless_conversion)] proc_macro2::TokenStream::from(self).into() } /// Creates a [`TokenParser`](crate::TokenParser) from this token stream. /// /// Allows to specify the length of the [peeker buffer](crate::TokenParser#peeking). #[cfg(feature = "parser")] fn parser_generic{}(self) -> crate::TokenParser { #[allow(clippy::useless_conversion)] proc_macro2::TokenStream::from(self).into() } } } } macro_rules! token_tree_ext { ($($a:literal, $token:literal, $is:ident, $as:ident, $into:ident, $variant:ident);+$(;)?) => { impl_via_trait! { mod token_tree_ext, token_tree2_ext { /// Generic extensions for impl TokenTreeExt "[`proc_macro::TokenTree`]", TokenTree2Ext "[`proc_macro2::TokenTree`]" for TokenTree { $( #[doc = concat!("Tests if the token tree is ", $a, " ", $token, ".")] #[must_use] fn $is(&self) -> bool { matches!(self, Self::$variant(_)) } #[doc = concat!("Get the [`", stringify!($variant), "`] inside this token tree, or [`None`] if it isn't ", $a, " ", $token, ".")] #[must_use] fn $as(&self) -> Option<&$variant> { if let Self::$variant(inner) = &self { Some(inner) } else { None } } #[doc = concat!("Get the [`", stringify!($variant), "`] inside this token tree, or [`None`] if it isn't ", $a, " ", $token, ".")] #[must_use] fn $into(self) -> Option<$variant> { if let Self::$variant(inner) = self { Some(inner) } else { None } } )* } } } }; } token_tree_ext!( "a", "group", is_group, group, into_group, Group; "an", "ident", is_ident, ident, into_ident, Ident; "a", "punctuation", is_punct, punct, into_punct, Punct; "a", "literal", is_literal, literal, into_literal, Literal; ); macro_rules! punctuations { ($($char:literal as $name:ident),*) => { impl_via_trait!{ /// Trait to test for punctuation impl TokenTreePunct for TokenTree { $(#[doc = concat!("Tests if the token is `", $char, "`")] #[must_use] fn $name(&self) -> bool { matches!(self, TokenTree::Punct(punct) if punct.$name()) })* /// Tests if token is followed by some none punctuation token or whitespace. #[must_use] fn is_alone(&self) -> bool { matches!(self, TokenTree::Punct(punct) if punct.is_alone()) } /// Tests if token is followed by another punct and can potentially be combined into /// a multi-character operator. #[must_use] fn is_joint(&self) -> bool { matches!(self, TokenTree::Punct(punct) if punct.is_joint()) } /// If sets the [`spacing`](Punct::spacing) of a punct to [`Alone`](Spacing::Alone). #[must_use] fn alone(self) -> Self { match self { Self::Punct(p) => Self::Punct(p.alone()), it => it } } } impl TokenTreePunct for Punct { $(fn $name(&self) -> bool { self.as_char() == $char })* fn is_alone(&self) -> bool { self.spacing() == Spacing::Alone } fn is_joint(&self) -> bool { self.spacing() == Spacing::Joint } fn alone(self) -> Self { if self.is_alone() { self } else { let mut this = Punct::new(self.as_char(), Spacing::Alone); this.set_span(self.span()); this } } } } }; } punctuations![ '=' as is_equals, '<' as is_less_than, '>' as is_greater_than, '!' as is_exclamation, '~' as is_tilde, '+' as is_plus, '-' as is_minus, '*' as is_asterix, // TODO naming '/' as is_slash, '%' as is_percent, '^' as is_caret, '&' as is_and, '|' as is_pipe, '@' as is_at, '.' as is_dot, ',' as is_comma, ';' as is_semi, ':' as is_colon, '#' as is_pound, '$' as is_dollar, '?' as is_question, '\'' as is_quote // TODO naming ]; macro_rules! delimited { ($($delimiter:ident as $name:ident : $doc:literal),*) => { impl_via_trait!{ /// Trait to test for delimiters of groups impl Delimited for TokenTree { $(#[doc = concat!("Tests if the token is a group with ", $doc)] #[must_use] fn $name(&self) -> bool { matches!(self, TokenTree::Group(group) if group.$name()) })* } impl Delimited for Group { $(#[doc = concat!("Tests if a group has ", $doc)] #[must_use] fn $name(&self) -> bool { matches!(self.delimiter(), Delimiter::$delimiter) })* } } }; } delimited![ Parenthesis as is_parenthesized: " parentheses (`( ... )`)", Brace as is_braced: " braces (`{ ... }`)", Bracket as is_bracketed: " brackets (`[ ... ]`)", None as is_implicitly_delimited: " no delimiters (`Ø ... Ø`)" ]; impl_via_trait! { /// Trait to parse literals impl TokenTreeLiteral for TokenTree { /// Tests if the token is a string literal. #[must_use] fn is_string(&self) -> bool { self.literal().is_some_and(TokenTreeLiteral::is_string) } /// Returns the string contents if it is a string literal. #[must_use] fn string(&self) -> Option { self.literal().and_then(TokenTreeLiteral::string) } } impl TokenTreeLiteral for Literal { fn is_string(&self) -> bool { let s = self.to_string(); s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") } fn string(&self) -> Option { let lit = self.to_string(); if lit.starts_with('"') { Some(resolve_escapes(&lit[1..lit.len() - 1])) } else if lit.starts_with('r') { let pounds = lit.chars().skip(1).take_while(|&c| c == '#').count(); Some(lit[2 + pounds..lit.len() - pounds - 1].to_owned()) } else { None } } } } // Implemented following https://doc.rust-lang.org/reference/tokens.html#string-literals // #[allow(clippy::needless_continue)] fn resolve_escapes(mut s: &str) -> String { let mut out = String::new(); while !s.is_empty() { if s.starts_with('\\') { match s.as_bytes()[1] { b'x' => { out.push( char::from_u32(u32::from_str_radix(&s[2..=3], 16).expect("valid escape")) .expect("valid escape"), ); s = &s[4..]; } b'u' => { let len = s[3..].find('}').expect("valid escape"); out.push( char::from_u32(u32::from_str_radix(&s[3..len], 16).expect("valid escape")) .expect("valid escape"), ); s = &s[3 + len..]; } b'n' => { out.push('\n'); s = &s[2..]; } b'r' => { out.push('\r'); s = &s[2..]; } b't' => { out.push('\t'); s = &s[2..]; } b'\\' => { out.push('\\'); s = &s[2..]; } b'0' => { out.push('\0'); s = &s[2..]; } b'\'' => { out.push('\''); s = &s[2..]; } b'"' => { out.push('"'); s = &s[2..]; } b'\n' => { s = &s[..s[2..] .find(|c: char| !c.is_ascii_whitespace()) .unwrap_or(s.len())]; } c => unreachable!( "TokenStream string literals should only contain valid escapes, found `\\{c}`" ), } } else { let len = s.find('\\').unwrap_or(s.len()); out.push_str(&s[..len]); s = &s[len..]; } } out } #[cfg(all(test, feature = "proc-macro2"))] mod test { use proc_macro2::{Punct, Spacing, TokenTree}; use quote::quote; use super::*; #[test] fn punctuation() { let mut tokens = quote! {=<>!$~+-*/%^|@.,;:#$?'a}.into_iter(); assert!(tokens.next().unwrap().is_equals()); assert!(tokens.next().unwrap().is_less_than()); assert!(tokens.next().unwrap().is_greater_than()); assert!(tokens.next().unwrap().is_exclamation()); assert!(tokens.next().unwrap().is_dollar()); assert!(tokens.next().unwrap().is_tilde()); assert!(tokens.next().unwrap().is_plus()); assert!(tokens.next().unwrap().is_minus()); assert!(tokens.next().unwrap().is_asterix()); assert!(tokens.next().unwrap().is_slash()); assert!(tokens.next().unwrap().is_percent()); assert!(tokens.next().unwrap().is_caret()); assert!(tokens.next().unwrap().is_pipe()); assert!(tokens.next().unwrap().is_at()); assert!(tokens.next().unwrap().is_dot()); assert!(tokens.next().unwrap().is_comma()); assert!(tokens.next().unwrap().is_semi()); assert!(tokens.next().unwrap().is_colon()); assert!(tokens.next().unwrap().is_pound()); assert!(tokens.next().unwrap().is_dollar()); assert!(tokens.next().unwrap().is_question()); assert!(tokens.next().unwrap().is_quote()); } #[test] fn token_stream_ext() { let mut tokens = quote!(a); tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone))); assert_eq!(tokens.to_string(), "a ,"); } #[test] fn token_tree_ext() { let mut tokens = quote!({group} ident + "literal").into_iter().peekable(); assert!(tokens.peek().unwrap().is_group()); assert!(matches!( tokens.next().unwrap().group().unwrap().to_string().as_str(), "{ group }" | "{group}" )); assert!(tokens.peek().unwrap().is_ident()); assert_eq!(tokens.next().unwrap().ident().unwrap().to_string(), "ident"); assert!(tokens.peek().unwrap().is_punct()); assert_eq!(tokens.next().unwrap().punct().unwrap().to_string(), "+"); assert!(tokens.peek().unwrap().is_literal()); assert_eq!( tokens.next().unwrap().literal().unwrap().to_string(), "\"literal\"" ); } #[test] fn test() {} } proc-macro-utils-0.10.0/src/parser.rs000064400000000000000000001350311046102023000155360ustar 00000000000000use std::ops::{Bound, RangeBounds}; use std::str::FromStr; use std::{iter, mem}; #[cfg(doc)] use proc_macro2::Spacing; use proc_macro2::{token_stream, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; use smallvec::{smallvec, SmallVec}; use crate::{Delimited, TokenStream2Ext, TokenTree2Ext, TokenTreeLiteral, TokenTreePunct}; // TODO move implementation in a trait implemented on both // Peekables /// Trait that allows to peek a constant number of tokens. pub trait Peeker { /// Number of tokens this peeker checks. fn len(&self) -> usize; /// Test if the tokens match. /// /// # Panics /// /// Implementations can panic if `tokens.len() < Self::LENGTH`. #[must_use] fn peek(self, tokens: &[TokenTree]) -> bool; } impl bool> Peeker for T { fn len(&self) -> usize { 1 } #[must_use] fn peek(self, parser: &[TokenTree]) -> bool { self(&parser[0]) } } macro_rules! impl_peeker { ($(($($T:ident $idx:tt),+$(,)?),$len:literal;)*) => { $( impl<$($T: FnOnce(&TokenTree) -> bool),+> Peeker for ($($T,)+) { fn len(&self) -> usize { $len } fn peek(self, parser: &[TokenTree]) -> bool { $(self.$idx(&parser[$idx]))&&+ } } )* }; } impl_peeker![ (T1 0,), 1; (T1 0, T2 1), 2; (T1 0, T2 1, T3 2), 3; ]; struct PeekLen(usize); impl Peeker for PeekLen { fn len(&self) -> usize { self.0 } fn peek(self, _: &[TokenTree]) -> bool { true } } /// Wrapper for [`TokenStream::into_iter`] allowing not only to iterate on /// tokens but also to parse simple structures like types or expressions, though /// it does not make any claims about their correctness. /// /// ``` /// # use proc_macro2::TokenStream; /// # use proc_macro_utils::{TokenParser, assert_tokens}; /// # use quote::quote; /// let mut token_parser = TokenParser::new(quote! {a + b, c}); /// assert_tokens!(token_parser.next_expression().unwrap(), { a + b }); /// ``` /// /// # Construction /// /// In most cases use [`new()`](TokenParser::new) to avoid specifying the /// generics. To change the on-stack size of the peek-buffer use /// [`new_generic()`](TokenParser::new_generic) or /// [`From::from`](#impl-From-for-TokenParser). /// /// # Peeking /// /// The `TokenParser` allows peeking an arbitrary amount of tokens using /// [`peek_n()`](Self::peek_n) and the token specific variants. This uses a /// [`SmallVec`] with its capacity specified via `PEEKER_LEN` (default is 6). /// This means peeking up to `6` tokens ahead happens without heap allocation. /// Token groups can need up to `3` tokens of additional space e.g. /// [`peek_n_tt_dot_dot_eq()`](Self::peek_n_tt_dot_dot_eq) can, with the default /// allocation free be called with up to `3`, and /// [`peek_n_tt_plus_eq()`](Self::peek_n_tt_plus_eq) up to `4`. /// /// **Warning**: Setting `PEEKER_LEN = 0` means even /// [`is_empty()`](Self::is_empty) and [`peek()`](Self::peek) allocate, and a /// value below `3` will make some of the /// [`peek_{punctuation}`](#impl-TokenParser-3) allocate /// additionally. But do also refrain from setting `PEEKER_LEN` too high, as /// this is the stack allocation used. #[allow(clippy::module_name_repetitions)] #[derive(Clone)] #[must_use] pub struct TokenParser< I: Iterator = token_stream::IntoIter, const PEEKER_LEN: usize = 6, > { peek: SmallVec<[TokenTree; PEEKER_LEN]>, iter: I, } impl TokenParser { /// Creates a new [`TokenParser`] from a [`TokenTree`] iterator. /// /// This sets the default length for the peeker buffer. Use /// [`new_generic()`](Self::new_generic) to change it. pub fn new(value: T) -> TokenParser where T: IntoIterator, I: Iterator, { TokenParser::new_generic(value) } /// Creates a new [`TokenParser`] from a [`TokenTree`] iterator, allowing /// to specify the size of the peeker buffer. /// /// See [Peeking](#Peeking) for implications. pub fn new_generic(value: T) -> TokenParser where T: IntoIterator, I: Iterator, { TokenParser { peek: smallvec![], iter: value.into_iter(), } } } impl From for TokenParser where T: IntoIterator, I: Iterator, { fn from(value: T) -> Self { TokenParser::new_generic(value) } } impl From> for TokenStream where I: Iterator, { #[must_use] fn from(value: TokenParser) -> Self { value.peek.into_iter().chain(value.iter).collect() } } impl Iterator for TokenParser where I: Iterator, { type Item = TokenTree; #[must_use] fn next(&mut self) -> Option { if self.peek.is_empty() { self.iter.next() } else { Some(self.peek.remove(0)) } } } impl FromStr for TokenParser { type Err = ::Err; fn from_str(s: &str) -> Result { TokenStream::from_str(s).map(Self::new) } } #[cfg(feature = "quote")] impl quote::ToTokens for TokenParser where I: Clone + Iterator, { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.clone()); } #[must_use] fn to_token_stream(&self) -> TokenStream { self.clone().collect() } #[must_use] fn into_token_stream(self) -> TokenStream where Self: Sized, { self.collect() } } macro_rules! next_punct { ($self:ident, $only:ident) => { $self.next_if(TokenTree::$only).map(TokenTree::alone).map(iter::once).map(Iterator::collect) }; ($self:ident, $($joint:ident),+ $(!$($not:ident),+)?) => { next_punct!($self, 0, $($joint),+ $(!$($not),+)?;true) }; ($self:ident, $idx:expr, $first:ident, $($joint:ident),+ $(!$($not:ident),*)?;$($cond:tt)*) => { next_punct!($self, $idx+1, $($joint),+ $(!$($not),+)?; $($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$first() && tt.is_joint())) }; ($self:ident, $idx:expr, $last:ident;$($cond:tt)*) => { ($($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$last())).then(|| $self.next_n_alone($idx+1).expect("peeked n")) }; ($self:ident, $idx:expr, $last:ident !$($not:ident),+;$($cond:tt)*) => { ($($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$last()) && (matches!($self.peek_n($idx), Some(tt) if tt.is_alone()) || !(matches!($self.peek_n($idx+1), Some(tt) if false $(|| tt.$not())*)))) .then(|| $self.next_n_alone($idx+1).expect("peeked n")) }; } macro_rules! peek_punct { ($offset:expr, $self:ident, $only:ident) => { $self.peek_n($offset).filter(|t| t.$only()).cloned().map(TokenTree::alone).map(iter::once).map(Iterator::collect) }; ($offset:expr, $self:ident, $($joint:ident),+ $(!$($not:ident),+)?) => { peek_punct!($offset, $self, $offset, $($joint),+ $(!$($not),+)?;true) }; ($offset:expr, $self:ident, $idx:expr, $first:ident, $($joint:ident),+ $(!$($not:ident),*)?;$($cond:tt)*) => { peek_punct!($offset, $self, $idx+1, $($joint),+ $(!$($not),+)?; $($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$first() && tt.is_joint())) }; ($offset:expr, $self:ident, $idx:expr, $last:ident;$($cond:tt)*) => { ($($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$last())).then(|| $self.peek_range_alone($offset..$idx+1).expect("peeked n")) }; ($offset:expr, $self:ident, $idx:expr, $last:ident !$($not:ident),+;$($cond:tt)*) => { ($($cond)* && matches!($self.peek_n($idx), Some(tt) if tt.$last()) && (matches!($self.peek_n($idx), Some(tt) if tt.is_alone()) || !(matches!($self.peek_n($idx+1), Some(tt) if false $(|| tt.$not())*)))) .then(|| $self.peek_range_alone($offset..$idx+1).expect("peeked n")) }; } macro_rules! punct_tt { ($($punct:literal, [$($cond:tt)*], $peek:ident, $peek_n:ident, $name:ident);*$(;)?) => { $(#[doc = concat!("Returns the next token if it is a [punctuation token tree](https://doc.rust-lang.org/reference/tokens.html#punctuation) `", $punct ,"` following the same rules as [macro_rule's tt](https://doc.rust-lang.org/reference/macros-by-example.html#metavariables).")] #[doc = concat!("``` use proc_macro_utils::{assert_tokens, TokenParser}; use quote::quote; let mut parser = TokenParser::new(quote!(", $punct, " 1 b)); assert_tokens!(parser.", stringify!($name), "().unwrap(), { ", $punct, " }); assert_tokens!(parser, { 1 b }); ```")] #[must_use] pub fn $name(&mut self) -> Option { next_punct!(self, $($cond)*) } #[doc = concat!("Returns the next token if it is a [punctuation token tree](https://doc.rust-lang.org/reference/tokens.html#punctuation) `", $punct ,"` following the same rules as [macro_rule's tt](https://doc.rust-lang.org/reference/macros-by-example.html#metavariables) without advancing the parser")] #[doc = concat!("``` use proc_macro_utils::{assert_tokens, TokenParser}; use quote::quote; let mut parser = TokenParser::new(quote!(", $punct, " 1 b)); assert_tokens!(parser.", stringify!($peek), "().unwrap(), { ", $punct, " }); ```")] #[must_use] pub fn $peek(&mut self) -> Option { peek_punct!(0, self, $($cond)*) } #[doc = concat!("Returns the `n`th token if it is a [punctuation token tree](https://doc.rust-lang.org/reference/tokens.html#punctuation) `", $punct ,"` following the same rules as [macro_rule's tt](https://doc.rust-lang.org/reference/macros-by-example.html#metavariables) without advancing the parser")] #[doc = concat!("``` use proc_macro_utils::{assert_tokens, TokenParser}; use quote::quote; let mut parser = TokenParser::new(quote!(b ", $punct, " 1)); assert_tokens!(parser.", stringify!($peek_n), "(1).unwrap(), { ", $punct, " }); ```")] #[must_use] pub fn $peek_n(&mut self, n: usize) -> Option { peek_punct!(n, self, $($cond)*) })* /// Returns the next token tree as interpreted by the `tt` type in `macro_rules`, i.e., any literal, group, /// or [composed punctuation](https://doc.rust-lang.org/reference/tokens.html#punctuation). pub fn next_tt(&mut self) -> Option { self.next_if_each(TokenTree::is_group) .or_else(|| self.next_if_each(TokenTree::is_literal)) $(.or_else(|| self.$name()))* } /// Peeks the next token tree as interpreted by the `tt` type in `macro_rules`, i.e., any literal, group, /// or [composed punctuation](https://doc.rust-lang.org/reference/tokens.html#punctuation). pub fn peek_tt(&mut self) -> Option { self.peek_n_tt(0) } /// Peeks the next token tree from the `n`th token as interpreted by the `tt` type in `macro_rules`, i.e., any literal, group, /// or [composed punctuation](https://doc.rust-lang.org/reference/tokens.html#punctuation). pub fn peek_n_tt(&mut self, n: usize) -> Option { self.peek_if_each(TokenTree::is_group) .or_else(|| self.peek_if_each(TokenTree::is_literal)) $(.or_else(|| self.$peek_n(n)))* } }; ([$test:ident $($tests:ident)*]) => { matches!(self.peek(), Some(token) if token.$test()) && punct!([$($tests)*]) } } macro_rules! token_tree { ($($a:literal, $test:ident, $peek_as:ident, $as:ident, $peek:ident, $peek_n:ident, $name:ident, $token:ident);*$(;)?) => { $(#[doc = concat!("Returns the next token if it is ", $a, " [`", stringify!($token) ,"`].")] #[must_use] pub fn $name(&mut self) -> Option<$token> { self.$peek().is_some().then(|| self.next().expect("token should be present").$as().expect(concat!("should be ", stringify!($token)))) })* $(#[doc = concat!("Returns the next token if it is ", $a, " [`", stringify!($token) ,"`] without advancing the parser.")] #[must_use] pub fn $peek(&mut self) -> Option<&$token> { self.$peek_n(0) })* $(#[doc = concat!("Returns the `n`th token if it is ", $a, " [`", stringify!($token) ,"`] without advancing the parser.")] #[must_use] pub fn $peek_n(&mut self, n: usize) -> Option<&$token> { self.peek_n(n).and_then(TokenTree::$peek_as) })* }; } macro_rules! delimited { ($($test:ident, $peek:ident, $peek_n:ident, $name:ident, $doc:literal;)*) => { $(#[doc = concat!("Returns the next token if it is a ", $doc ," group.")] #[must_use] pub fn $name(&mut self) -> Option { self.$peek().is_some().then(|| { self.next_group().unwrap() }) })* $(#[doc = concat!("Returns the next token if it is a", $doc ," group, without advancing the parser.")] #[must_use] pub fn $peek(&mut self) -> Option<&Group> { self.$peek_n(0) })* $(#[doc = concat!("Returns the `n`th token if it is a ", $doc ," group, without advancing the parser.")] #[must_use] pub fn $peek_n(&mut self, n: usize) -> Option<&Group> { self.peek_n_group(n).filter(|g| g.$test()) })* }; } /// Some Iterator utilities impl TokenParser where I: Iterator, { /// Returns span of the next token or [`Span::call_site()`]. #[must_use] pub fn span(&mut self) -> Span { self.peek().map_or_else(Span::call_site, TokenTree::span) } /// Checks if there are remaining tokens /// ``` /// use proc_macro_utils::TokenParser; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(token)); /// assert!(!parser.is_empty()); /// _ = parser.next(); /// assert!(parser.is_empty()) /// ``` #[must_use] pub fn is_empty(&mut self) -> bool { self.peek().is_none() } /// Peeks the next token without advancing the parser /// ``` /// use proc_macro_utils::{assert_tokens, TokenParser}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(token)); /// assert_tokens!(parser.peek().cloned(), { token }); /// _ = parser.next(); /// assert!(parser.peek().is_none()) /// ``` #[must_use] pub fn peek(&mut self) -> Option<&TokenTree> { if self.peek.is_empty() { self.peek.push(self.iter.next()?); } self.peek.first() } /// Peeks the `n`th token without advancing the parser /// ``` /// use proc_macro_utils::{assert_tokens, TokenParser}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(token , third)); /// assert_tokens!(parser.peek_n(2).cloned(), { third }); /// assert_tokens!(parser.peek_n(1).cloned(), { , }); /// assert!(parser.peek_n(3).is_none()) /// ``` #[must_use] pub fn peek_n(&mut self, n: usize) -> Option<&TokenTree> { for _ in self.peek.len()..=n { self.peek.push(self.iter.next()?); } self.peek.get(n) } /// Returns the next token if it fulfills the condition otherwise returns /// None and doesn't advance the parser /// ``` /// use proc_macro_utils::{assert_tokens, TokenParser, TokenTreePunct}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(::)); /// assert!(parser.next_if(TokenTreePunct::is_alone).is_none()); /// _ = parser.next(); /// assert_tokens!(parser.next_if(TokenTreePunct::is_alone), { : }); /// ``` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_if(&mut self, test: impl FnOnce(&TokenTree) -> bool) -> Option { test(self.peek()?).then(|| self.next().expect("was peeked")) } /// Returns the next tokens if they fulfill the conditions /// otherwise returns None and doesn't advance the parser. /// ``` /// use proc_macro_utils::{assert_tokens, TokenParser, TokenTreePunct}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!( -->)); /// assert!(parser.next_if_each((TokenTreePunct::is_minus, TokenTreePunct::is_greater_than)).is_none()); /// _ = parser.next(); /// assert_tokens!(parser.next_if_each((TokenTreePunct::is_minus, TokenTreePunct::is_greater_than)).unwrap(), { -> }); /// ``` #[must_use] pub fn next_if_each(&mut self, tests: P) -> Option { let len = tests.len(); // Ensure peek is filled; self.peek_n(len - 1)?; tests .peek(&self.peek[..len]) .then(|| self.peek.drain(0..len).collect()) } /// Returns the next tokens if they fulfill the conditions /// otherwise returns None and doesn't advance the parser. If the last token /// is a punct it's [`spacing`](Punct::spacing()) is set to /// [`Alone`](Spacing::Alone). #[must_use] pub fn next_if_each_alone(&mut self, tests: P) -> Option { let len = tests.len(); // Ensure peek is filled; self.peek_n(len - 1)?; tests.peek(&self.peek[..len]).then(|| { if self.peek[len - 1].is_punct() { self.peek[len - 1] = self.peek[len - 1].clone().alone(); } self.peek.drain(0..len).collect() }) } /// Returns the next tokens if they fulfill the conditions /// otherwise returns None, without advancing the parser #[must_use] pub fn peek_if_each(&mut self, tests: P) -> Option { // Ensure peek is filled; self.peek_n_if_each(0, tests) } /// Returns the next tokens from `n` if they fulfill the /// conditions otherwise returns None, without advancing the parser #[must_use] pub fn peek_n_if_each(&mut self, n: usize, tests: P) -> Option { let len = tests.len(); // Ensure peek is filled; self.peek_n(len + n)?; let peeked = &self.peek[n..len + n]; tests.peek(peeked).then(|| peeked.iter().cloned().collect()) } /// Returns the next tokens from `n` if they fulfill the conditions /// otherwise returns None, without advancing the parser. If the last token /// is a punct it's [`spacing`](Punct::spacing()) is set to /// [`Alone`](Spacing::Alone). #[must_use] pub fn peek_n_if_each_alone(&mut self, n: usize, tests: P) -> Option { let len = tests.len(); if len == 0 { return Some(TokenStream::new()); } // Ensure peek is filled; self.peek_n(len + n - 1)?; let peeked = &self.peek[n..len + n]; tests.peek(peeked).then(|| { peeked[..len - 1] .iter() .cloned() .chain(iter::once(peeked[len - 1].clone().alone())) .collect() }) } /// Returns all tokens while `test` evaluates to true. /// /// Returns `None` if empty or `test(first_token) == false` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_while(&mut self, mut test: impl FnMut(&TokenTree) -> bool) -> Option { if self.peek().is_none() || !test(self.peek().expect("was peeked")) { None } else { let mut token_stream = TokenStream::new(); token_stream.push(self.next().expect("was peeked")); while let Some(token) = self.next_if(&mut test) { token_stream.push(token); } Some(token_stream) } } /// Returns all tokens while `test` evaluates to true. If the last token /// is a punct it's [`spacing`](Punct::spacing()) is set to /// [`Alone`](Spacing::Alone). /// /// Returns `None` if empty or `test(first_token) == false` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_while_alone( &mut self, mut test: impl FnMut(&TokenTree) -> bool, ) -> Option { if self.peek().is_none() || !test(self.peek().expect("was peeked")) { None } else { let mut token_stream = TokenStream::new(); let mut last = self.next().expect("was peeked"); while let Some(token) = self.next_if(&mut test) { token_stream.push(mem::replace(&mut last, token)); } token_stream.push(last.alone()); Some(token_stream) } } /// Returns all tokens while `test` evaluates to false. /// /// Returns `None` if empty or `test(first_token) == true`. #[must_use] pub fn next_until(&mut self, mut test: impl FnMut(&TokenTree) -> bool) -> Option { self.next_while(|token| !test(token)) } /// Returns all tokens while `test` evaluates to false. If the last token is /// a punct it's [`spacing`](Punct::spacing()) is set to /// [`Alone`](Spacing::Alone). /// /// Returns `None` if empty or `test(first_token) == true`. #[must_use] pub fn next_until_alone( &mut self, mut test: impl FnMut(&TokenTree) -> bool, ) -> Option { self.next_while_alone(|token| !test(token)) } /// Returns the next `n` tokens. /// /// Returns `None` if the parser contains less than `n` tokens. /// /// **Note:** This should only be used for small `n` ideally less than /// `PEEKER_LEN`. Otherwise, something like this would be more performant: /// ``` /// use proc_macro2::TokenStream; /// use proc_macro_utils::{TokenParser, assert_tokens}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(1 2 3 /*...*/ 1000 1001 1002 1003)); /// let n = 1000; /// # let n = 4; /// // This does not ensure that `next_up_to_n` contains exactly n tokens /// let next_up_to_n: TokenStream = parser.by_ref().take(n).collect(); /// assert_tokens!(next_up_to_n, { 1 2 3 /* ...*/ 1000 }); /// assert_tokens!(parser, { 1001 1002 1003 }); /// ``` #[must_use] pub fn next_n(&mut self, n: usize) -> Option { self.next_if_each(PeekLen(n)) } /// Returns the next `n` tokens. If the last token is a punct it's /// [`spacing`](Punct::spacing()) is set to [`Alone`](Spacing::Alone). /// /// Returns `None` if the parser contains less than `n` tokens. /// /// **Note:** This should only be used for small `n` ideally less than /// `PEEKER_LEN`. Otherwise, something like this would be more performant: /// ``` /// use proc_macro2::TokenStream; /// use proc_macro_utils::{TokenParser, assert_tokens, TokenTreePunct}; /// use quote::quote; /// /// let mut parser = TokenParser::new(quote!(1 2 3 /*...*/ 1000 1001 1002 1003)); /// let n = 1000; /// # let n = 4; /// // This does not ensure that `next_up_to_n` contains exactly n tokens /// let mut next_up_to_n: TokenStream = parser.by_ref().take(n - 1).collect(); /// next_up_to_n.extend(parser.next().map(TokenTreePunct::alone)); /// assert_tokens!(next_up_to_n, { 1 2 3 /* ...*/ 1000 }); /// assert_tokens!(parser, { 1001 1002 1003 }); /// ``` #[must_use] pub fn next_n_alone(&mut self, n: usize) -> Option { self.next_if_each_alone(PeekLen(n)) } /// Returns the specified `range` of tokens. /// /// Returns `None` if the parser does not contain these `range` tokens. /// /// **Note:** This should only be used for small and close to start `range`s /// ideally less than `PEEKER_LEN`. Otherwise, something like this could be /// more performant: /// ``` /// use proc_macro2::TokenStream; /// use proc_macro_utils::{TokenParser, assert_tokens}; /// use quote::quote; /// /// let parser = TokenParser::new(quote!(0 1 2 3 /*...*/ 1000 1001 1002 1003)); /// let start = 1000; /// # let start = 4; /// let end = 1003; /// # let end = 7; /// // This does not ensure that `peeked_range` contains any tokens /// let peeked_range: TokenStream = parser.clone().skip(start).take(end - /// start).collect(); /// assert_tokens!(peeked_range, { 1000 1001 1002 }); /// assert_tokens!(parser, { 0 1 2 3 /*...*/ 1000 1001 1002 1003 }); /// ``` /// /// # Panics /// /// Panics if used without upper bound i.e. `start..`. #[must_use] pub fn peek_range(&mut self, range: impl RangeBounds) -> Option { let start = match range.start_bound() { Bound::Included(&n) => n, Bound::Excluded(&n) => n + 1, Bound::Unbounded => 0, }; let len = match range.end_bound() { Bound::Included(&n) if n < start => return None, Bound::Included(&n) => n - start + 1, Bound::Excluded(&n) if n <= start => return None, Bound::Excluded(&n) => n - start, Bound::Unbounded => { panic!("unbounded range not supported, use `clone().skip()` instead") } }; self.peek_n_if_each(start, PeekLen(len)) } /// Returns the specified `range` of tokens. If the last token is a punct /// it's [`spacing`](Punct::spacing()) is set to /// [`Alone`](Spacing::Alone). /// /// Returns `None` if the parser does not contain these `range` tokens. /// /// **Note:** This should only be used for small and close to start `range`s /// ideally less than `PEEKER_LEN`. Otherwise, something like this could be /// more performant: /// /// ``` /// use proc_macro2::TokenStream; /// use proc_macro_utils::{assert_tokens, TokenParser, TokenTreePunct}; /// use quote::quote; /// /// let parser = TokenParser::new(quote!(0 1 2 3 /*...*/ 1000 1001 1002 1003)); /// let start = 1000; /// # let start = 4; /// let end = 1003; /// # let end = 7; /// // This does not ensure that `peeked_range` contains any tokens /// let mut cloned = parser.clone().skip(start); /// let mut peeked_range: TokenStream = cloned.by_ref().take(end - start - 1).collect(); /// peeked_range.extend(cloned.next().map(TokenTreePunct::alone)); /// /// assert_tokens!(peeked_range, { 1000 1001 1002 }); /// assert_tokens!(parser, { 0 1 2 3 /*...*/ 1000 1001 1002 1003 }); /// ``` /// /// # Panics /// /// Panics if used without upper bound i.e. `start..`. #[must_use] pub fn peek_range_alone(&mut self, range: impl RangeBounds) -> Option { let start = match range.start_bound() { Bound::Included(&n) => n, Bound::Excluded(&n) => n + 1, Bound::Unbounded => 0, }; let len = match range.end_bound() { Bound::Included(&n) if n < start => return None, Bound::Included(&n) => n - start + 1, Bound::Excluded(&n) if n <= start => return None, Bound::Excluded(&n) => n - start, Bound::Unbounded => { panic!("unbounded range not supported, use `clone().skip()` instead") } }; self.peek_n_if_each_alone(start, PeekLen(len)) } } impl TokenParser where I: Iterator, { /// Collects remaining tokens back into a [`TokenStream`] #[must_use] pub fn into_token_stream(self) -> TokenStream { self.into() } /// Returns the next group of punctuation with [`Punct::spacing`] /// [`Spacing::Joint`] #[must_use] pub fn next_punctuation_group(&mut self) -> Option { let mut joined = true; self.next_while(move |token| { let ret = joined && token.is_punct(); joined = token.is_joint(); ret }) } /// Returns the next ident if it matches the specified keyword without /// advancing the parser. /// /// While this is called `peek_keyword` it is not restricted to rust /// keywords, it can be used with any ident. /// ``` /// # use proc_macro_utils::TokenParser; /// # use quote::quote; /// let mut parser = TokenParser::new(quote!( in out )); /// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in"); /// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in"); /// assert!(parser.peek_keyword("out").is_none()); /// parser.next().unwrap(); /// assert_eq!(parser.peek_keyword("out").unwrap().to_string(), "out"); /// ``` #[must_use] pub fn peek_keyword(&mut self, keyword: &K) -> Option<&Ident> where Ident: PartialEq, { self.peek_n_keyword(0, keyword) } /// Returns the nth token if it matches the specified keyword without /// advancing the parser. /// /// While this is called `peek_n_keyword` it is not restricted to rust /// keywords, it can be used with any ident. /// ``` /// # use proc_macro_utils::TokenParser; /// # use quote::quote; /// let mut parser = TokenParser::new(quote!( in out )); /// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in"); /// assert_eq!(parser.peek_n_keyword(1, "out").unwrap().to_string(), "out"); /// assert!(parser.peek_keyword("out").is_none()); /// ``` #[must_use] pub fn peek_n_keyword(&mut self, n: usize, keyword: &K) -> Option<&Ident> where Ident: PartialEq, { self.peek_n_ident(n).filter(|&ident| ident == keyword) } /// Returns the next ident if it matches the specified keyword. /// /// While this is called `next_keyword` it is not restricted to rust /// keywords, it can be used with any ident. /// ``` /// # use proc_macro_utils::TokenParser; /// # use quote::quote; /// let mut parser = TokenParser::new(quote!( in out )); /// assert_eq!(parser.next_keyword("in").unwrap().to_string(), "in"); /// assert!(parser.next_keyword("in").is_none()); /// assert_eq!(parser.next_keyword("out").unwrap().to_string(), "out"); /// assert!(parser.next_keyword("anything").is_none()); /// ``` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_keyword(&mut self, keyword: &K) -> Option where Ident: PartialEq, { self.next_if(|token| matches!(token.ident(), Some(ident) if ident == keyword)) .map(|token| token.into_ident().expect("is ident")) } /// "Parses" a type expression /// /// This just means it collects all the tokens that should belong to the /// type, until it reaches either: /// - a `;` /// - a `,` or `>` and all `<>` pairs are closed /// - the end of the token stream /// /// If the token stream is empty, or starts with `,`, `>` or `;` [`None`] is /// returned otherwise, [`Some(TokenStream)`](TokenStream) containing /// every token up to but excluding the terminator. /// /// ``` /// # use proc_macro_utils::{TokenParser, assert_tokens}; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// /// let mut tokens = TokenParser::new(quote! {A, remainder}); /// assert_tokens!(tokens.next_type().unwrap(), { A }); /// assert!(tokens.next_type().is_none()); /// assert_tokens!(tokens, { , remainder }); /// ``` #[must_use] pub fn next_type(&mut self) -> Option { let first = self.peek()?; if first.is_comma() || first.is_semi() { return None; }; let mut chevron_level: u32 = 0; self.next_while_alone(|token| { if token.is_less_than() { chevron_level += 1; } else if token.is_greater_than() { if chevron_level == 0 { return false; } chevron_level -= 1; } !(chevron_level == 0 && token.is_comma() || token.is_semi()) }) } /// "Parses" an expression /// /// This just means it collects all the tokens that should belong to the /// expression, until it reaches (outside a group like `()` or `{}`) either: /// - a `=>` /// - a `;` /// - a `,` outside a type /// - the end of the token stream /// /// If the token stream is empty, or starts with `=>`, `,` or `;` [`None`] /// is returned otherwise, [`Some(TokenStream)`](TokenStream) containing /// every token up to but excluding the terminator. /// /// ``` /// # use proc_macro_utils::{TokenParser, assert_tokens}; /// # use proc_macro2::TokenStream; /// # use quote::quote; /// /// let mut tokens = TokenParser::new(quote! {A + c ::::a < b + ::C>::nice(), next_token}); /// assert_tokens!(tokens.next_expression().unwrap(), { A + c::::a < b + ::C>::nice()}); /// assert!(tokens.next_expression().is_none()); /// assert_tokens!(tokens, { , next_token }); /// ``` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_expression(&mut self) -> Option { if self.peek().is_none() || matches!(self.peek(), Some(token) if token.is_comma() || token.is_semi()) || self.peek_tt_fat_arrow().is_some() { return None; } let mut start = true; let mut tokens = TokenStream::new(); let mut last = None; // * // => 'outer: while let Some(token) = self.peek() { if token.is_semi() || token.is_comma() || self.peek_tt_fat_arrow().is_some() { break; } let token = self.peek().unwrap(); if start && token.is_less_than() { tokens.extend(mem::replace( &mut last, Some(self.next().expect("token was peeked")), )); loop { if let Some(ty) = self.next_type() { for token in ty { tokens.extend(mem::replace(&mut last, Some(token))); } } // next token can only be `,;>` or None let Some(token) = self.peek() else { break 'outer; }; // Invalid expression if token.is_semi() { break 'outer; } if token.is_greater_than() { tokens.extend(mem::replace( &mut last, Some(self.next().expect("token was peeked")), )); break; } else if token.is_comma() { tokens.extend(mem::replace( &mut last, Some(self.next().expect("token was peeked")), )); continue; // Another type }; } } if let Some(token) = self.next() { // TODO this might be too simplistic start = token.is_punct(); tokens.extend(mem::replace(&mut last, Some(token))); } } // ensure that the last punctuation is not joined (i.e. was touching the // terminator, mainly possible in `1..,`) tokens.extend(last.map(TokenTree::alone)); Some(tokens.into_iter().collect()) } /// Returns the next string literal #[must_use] pub fn next_string(&mut self) -> Option { let lit = self.peek().and_then(TokenTreeLiteral::string)?; self.next(); Some(lit) } /// Returns the next boolean literal #[must_use] pub fn next_bool(&mut self) -> Option { self.next_if(|t| { t.ident() .map_or(false, |ident| ident == "true" || ident == "false") }) .map(|t| matches!(t.ident(), Some(ident) if ident == "true")) } } impl TokenParser where I: Iterator, { token_tree!( "a", is_group, group, into_group, peek_group, peek_n_group, next_group, Group; "an", is_ident, ident, into_ident, peek_ident, peek_n_ident, next_ident, Ident; "a", is_punct, punct, into_punct, peek_punct, peek_n_punct, next_punct, Punct; "a", is_literal, literal, into_literal, peek_literal, peek_n_literal, next_literal, Literal; ); delimited!( is_parenthesized, peek_parenthesized, peek_n_parenthesized, next_parenthesized, "parenthesized"; is_braced, peek_braced, peek_n_braced, next_braced, "braced"; is_bracketed, peek_bracketed, peek_n_bracketed, next_bracketed, "bracketed"; ); } /// For now the naming of the tokens follow the names used in the /// [rust reference](https://doc.rust-lang.org/reference/tokens.html#punctuation) /// even though they diverge from the names used at [`TokenTreePunct`]. /// /// Note that they only match the token with correct [spacing](Spacing), i.e. /// [`next_plus`](Self::next_tt_plus) will match `+ =` and `+a` but not `+=`. // TODO figure out what the single token ones should return, TokenStream or // TokenTree impl TokenParser where I: Iterator, { punct_tt!( "+", [is_plus !is_equals], peek_tt_plus, peek_n_tt_plus, next_tt_plus; "-", [is_minus !is_equals], peek_tt_minus, peek_n_tt_minus, next_tt_minus; "*", [is_asterix !is_equals], peek_tt_star, peek_n_tt_star, next_tt_star; "/", [is_slash !is_equals], peek_tt_slash, peek_n_tt_slash, next_tt_slash; "%", [is_percent !is_equals], peek_tt_percent, peek_n_tt_percent, next_tt_percent; "^", [is_caret !is_equals], peek_tt_caret, peek_n_tt_caret, next_tt_caret; "!", [is_exclamation !is_equals], peek_tt_not, peek_n_tt_not, next_tt_not; "&", [is_and !is_equals, is_and], peek_tt_and, peek_n_tt_and, next_tt_and; "|", [is_pipe !is_equals, is_pipe], peek_tt_or, peek_n_tt_or, next_tt_or; "&&", [is_and, is_and !is_equals], peek_tt_and_and, peek_n_tt_and_and, next_tt_and_and; "||", [is_pipe, is_pipe !is_equals], peek_tt_or_or, peek_n_tt_or_or, next_tt_or_or; "<<", [is_less_than, is_less_than !is_equals], peek_tt_shl, peek_n_tt_shl, next_tt_shl; ">>", [is_greater_than, is_greater_than !is_equals], peek_tt_shr, peek_n_tt_shr, next_tt_shr; "+=", [is_plus, is_equals], peek_tt_plus_eq, peek_n_tt_plus_eq, next_tt_plus_eq; "-=", [is_minus, is_equals], peek_tt_minus_eq, peek_n_tt_minus_eq, next_tt_minus_eq; "*=", [is_asterix, is_equals], peek_tt_star_eq, peek_n_tt_star_eq, next_tt_star_eq; "/=", [is_slash, is_equals], peek_tt_slash_eq, peek_n_tt_slash_eq, next_tt_slash_eq; "%=", [is_percent, is_equals], peek_tt_percent_eq, peek_n_tt_percent_eq, next_tt_percent_eq; "^=", [is_caret, is_equals], peek_tt_caret_eq, peek_n_tt_caret_eq, next_tt_caret_eq; "&=", [is_and, is_equals], peek_tt_and_eq, peek_n_tt_and_eq, next_tt_and_eq; "|=", [is_pipe, is_equals], peek_tt_or_eq, peek_n_tt_or_eq, next_tt_or_eq; "<<=", [is_less_than, is_less_than, is_equals], peek_tt_shl_eq, peek_n_tt_shl_eq, next_tt_shl_eq; ">>=", [is_greater_than, is_greater_than, is_equals], peek_tt_shr_eq, peek_n_tt_shr_eq, next_tt_shr_eq; "=", [is_equals !is_equals], peek_tt_eq, peek_n_tt_eq, next_tt_eq; "==", [is_equals, is_equals], peek_tt_eq_eq, peek_n_tt_eq_eq, next_tt_eq_eq; "!=", [is_exclamation, is_equals], peek_tt_ne, peek_n_tt_ne, next_tt_ne; ">", [is_greater_than !is_equals], peek_tt_gt, peek_n_tt_gt, next_tt_gt; "<", [is_less_than !is_equals], peek_tt_lt, peek_n_tt_lt, next_tt_lt; ">=", [is_greater_than, is_equals], peek_tt_ge, peek_n_tt_ge, next_tt_ge; "<=", [is_less_than, is_equals], peek_tt_le, peek_n_tt_le, next_tt_le; "@", [is_at], peek_tt_at, peek_n_tt_at, next_tt_at; ".", [is_dot !is_dot], peek_tt_dot, peek_n_tt_dot, next_tt_dot; "..", [is_dot, is_dot !is_dot, is_equals], peek_tt_dot_dot, peek_n_tt_dot_dot, next_tt_dot_dot; "...", [is_dot, is_dot, is_dot], peek_tt_dot_dot_dot, peek_n_tt_dot_dot_dot, next_tt_dot_dot_dot; "..=", [is_dot, is_dot, is_equals], peek_tt_dot_dot_eq, peek_n_tt_dot_dot_eq, next_tt_dot_dot_eq; ",", [is_comma], peek_tt_comma, peek_n_tt_comma, next_tt_comma; ";", [is_semi], peek_tt_semi, peek_n_tt_semi, next_tt_semi; ":", [is_colon !is_colon], peek_tt_colon, peek_n_tt_colon, next_tt_colon; "::", [is_colon, is_colon], peek_tt_path_sep, peek_n_tt_path_sep, next_tt_path_sep; "->", [is_minus, is_greater_than], peek_tt_r_arrow, peek_n_tt_r_arrow, next_tt_r_arrow; "=>", [is_equals, is_greater_than], peek_tt_fat_arrow, peek_n_tt_fat_arrow, next_tt_fat_arrow; "#", [is_pound], peek_tt_pound, peek_n_tt_pound, next_tt_pound; "$", [is_dollar], peek_tt_dollar, peek_n_tt_dollar, next_tt_dollar; "?", [is_question], peek_tt_question, peek_n_tt_question, next_tt_question; "~", [is_tilde], peek_tt_tilde, peek_n_tt_tilde, next_tt_tilde; ); /// Returns the next token if it is a [punctuation token tree](https://doc.rust-lang.org/reference/tokens.html#punctuation) following the same rules as [macro_rule's `tt`](https://doc.rust-lang.org/reference/macros-by-example.html#metavariables). /// /// ``` /// use proc_macro_utils::{assert_tokens, TokenParser}; /// use quote::quote; /// let mut parser = TokenParser::new(quote!(.. =. 1 b)); /// assert_tokens!(parser.next_macro_rules_tt().unwrap(), { .. }); /// assert_tokens!(parser.next_macro_rules_tt().unwrap(), { = }); /// assert_tokens!(parser, { . 1 b }); /// ``` #[must_use] #[allow(clippy::missing_panics_doc)] pub fn next_macro_rules_tt(&mut self) -> Option { // ensure that the next 3 tokens are peeked if possible _ = self.peek_n(2); let first = self.peek.first().and_then(TokenTree::punct)?; let second = first .is_joint() .then(|| self.peek.get(1).and_then(TokenTree::punct)) .flatten(); let third = second .is_some_and(TokenTreePunct::is_joint) .then(|| self.peek.get(2).and_then(TokenTree::punct)) .flatten(); let chars = [ first.as_char(), second.map_or('_', Punct::as_char), third.map_or('_', Punct::as_char), ]; if matches!( chars, ['.', '.', '.' | '='] | ['<', '<', '='] | ['>', '>', '='] ) { self.next_n_alone(3) } else if matches!( &chars[0..2], ['&', '&' | '='] | ['|', '|' | '='] | ['<', '<' | '='] | ['>' | '-' | '=', '>'] | ['+' | '-' | '*' | '/' | '%' | '^' | '=' | '!' | '>', '='] | ['.', '.'] | [':', ':'] ) { self.next_n_alone(2) } else { self.next_n_alone(1) } } } #[cfg(test)] mod test { use quote::quote; use super::*; use crate::assert_tokens; #[test] fn ty() { let mut at = TokenParser::new(quote! {Name, }); assert_tokens!(at.next_type().unwrap(), { Name }); at.next(); assert_tokens!( at.next_type().unwrap(), { < Some , Generic , Type > } ); } #[test] fn expr() { let mut at = TokenParser::new( quote! {a + b, ::something + * a < b, "hi" => hello}, ); assert_tokens!(at.next_expression().unwrap(), { a + b }); at.next(); assert_tokens!( at.next_expression().unwrap(), { ::something + * a < b } ); at.next(); assert_tokens!(at.next_expression().unwrap(), { "hi" }); at.next(); at.next(); assert_tokens!(at.next_expression().unwrap(), { hello }); let mut at = TokenParser::from_str("1..,").unwrap(); let expr: Vec<_> = at.next_expression().unwrap().into_iter().collect(); assert!(expr.last().unwrap().is_alone()); assert_tokens!(expr, { 1.. }); } #[test] fn combined_tokens() { // using from_str to be able to verify behavior of splitting the input correctly // into tts let mut parser = TokenParser::from_str("->&&..=>=+,-..,+=").unwrap(); assert_tokens!(parser.next_tt_r_arrow().unwrap(), { -> }); assert_tokens!(parser.next_tt_and_and().unwrap(), { && }); assert_tokens!(parser.next_tt_dot_dot_eq().unwrap(), { ..= }); assert_tokens!(parser.next_tt_ge().unwrap(), { >= }); assert_tokens!(parser.next_tt_plus().unwrap(), { + }); assert_tokens!(parser.next_tt_comma().unwrap(), { , }); assert_tokens!(parser.next_tt_minus().unwrap(), { - }); assert_tokens!(parser.next_tt_dot_dot().unwrap(), { .. }); assert_tokens!(parser.next_tt_comma().unwrap(), { , }); assert_tokens!(parser.next_tt_plus_eq().unwrap(), { += }); } #[test] fn peek() { let mut parser = TokenParser::new(quote! { 0 {} 2 3 += .. = }); assert_eq!(parser.peek().unwrap().to_string(), "0"); assert_eq!(parser.peek_n(0).unwrap().to_string(), "0"); assert_eq!(parser.peek_n(1).unwrap().to_string().replace(' ', ""), "{}"); assert_eq!(parser.peek_n(2).unwrap().to_string(), "2"); assert_eq!(parser.peek_literal().unwrap().to_string(), "0"); assert!(parser.peek_group().is_none()); parser.next().unwrap(); assert!(parser.peek_group().is_some()); assert!(parser.peek_n_tt_plus_eq(3).is_some()); assert!(parser.peek_n_tt_dot_dot(5).is_some()); } #[test] fn keyword() { let mut parser: TokenParser<_, 4> = TokenParser::from(quote! { in out and or }); assert_eq!(parser.next_keyword("in").unwrap().to_string(), "in"); assert_eq!(parser.next_keyword("out").unwrap().to_string(), "out"); assert!(parser.next_keyword("or").is_none()); assert_eq!(parser.next_keyword("and").unwrap().to_string(), "and"); assert_eq!(parser.next_keyword("or").unwrap().to_string(), "or"); assert!(parser.next_keyword("or").is_none()); } }