seq-macro-0.3.5/.cargo_vcs_info.json0000644000000001360000000000100127300ustar { "git": { "sha1": "0f3c97e6cde1c78c700551a469d69aa9fde1f9ad" }, "path_in_vcs": "" }seq-macro-0.3.5/.github/FUNDING.yml000064400000000000000000000000201046102023000146650ustar 00000000000000github: dtolnay seq-macro-0.3.5/.github/workflows/ci.yml000064400000000000000000000036271046102023000162430ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.56.0] timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test msrv: name: Rust 1.46.0 needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@1.46.0 - run: cargo check clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 seq-macro-0.3.5/.gitignore000064400000000000000000000000361046102023000135070ustar 00000000000000/target **/*.rs.bk Cargo.lock seq-macro-0.3.5/Cargo.toml0000644000000022170000000000100107300ustar # 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 = "2018" rust-version = "1.45" name = "seq-macro" version = "0.3.5" authors = ["David Tolnay "] description = "Macro to repeat sequentially indexed copies of a fragment of code." documentation = "https://docs.rs/seq-macro" readme = "README.md" categories = [ "development-tools", "no-std", "no-std::no-alloc", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/seq-macro" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] proc-macro = true [dev-dependencies.rustversion] version = "1.0" [dev-dependencies.trybuild] version = "1.0.49" features = ["diff"] seq-macro-0.3.5/Cargo.toml.orig000064400000000000000000000012031046102023000144030ustar 00000000000000[package] name = "seq-macro" version = "0.3.5" authors = ["David Tolnay "] categories = ["development-tools", "no-std", "no-std::no-alloc"] description = "Macro to repeat sequentially indexed copies of a fragment of code." documentation = "https://docs.rs/seq-macro" edition = "2018" license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/seq-macro" rust-version = "1.45" [lib] proc-macro = true [dev-dependencies] rustversion = "1.0" trybuild = { version = "1.0.49", features = ["diff"] } [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] seq-macro-0.3.5/LICENSE-APACHE000064400000000000000000000227731046102023000134570ustar 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 perpetual, worldwide, non-exclusive, no-charge, 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 its 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 seq-macro-0.3.5/LICENSE-MIT000064400000000000000000000017771046102023000131700ustar 00000000000000Permission 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. seq-macro-0.3.5/README.md000064400000000000000000000051451046102023000130040ustar 00000000000000`seq!` ====== [github](https://github.com/dtolnay/seq-macro) [crates.io](https://crates.io/crates/seq-macro) [docs.rs](https://docs.rs/seq-macro) [build status](https://github.com/dtolnay/seq-macro/actions?query=branch%3Amaster) A `seq!` macro to repeat a fragment of source code and substitute into each repetition a sequential numeric counter. ```toml [dependencies] seq-macro = "0.3" ``` ```rust use seq_macro::seq; fn main() { let tuple = (1000, 100, 10); let mut sum = 0; // Expands to: // // sum += tuple.0; // sum += tuple.1; // sum += tuple.2; // // This cannot be written using an ordinary for-loop because elements of // a tuple can only be accessed by their integer literal index, not by a // variable. seq!(N in 0..=2 { sum += tuple.N; }); assert_eq!(sum, 1110); } ``` - If the input tokens contain a section surrounded by `#(` ... `)*` then only that part is repeated. - The numeric counter can be pasted onto the end of some prefix to form sequential identifiers. ```rust use seq_macro::seq; seq!(N in 64..=127 { #[derive(Debug)] enum Demo { // Expands to Variant64, Variant65, ... #( Variant~N, )* } }); fn main() { assert_eq!("Variant99", format!("{:?}", Demo::Variant99)); } ``` - Byte and character ranges are supported: `b'a'..=b'z'`, `'a'..='z'`. - If the range bounds are written in binary, octal, hex, or with zero padding, those features are preserved in any generated tokens. ```rust use seq_macro::seq; seq!(P in 0x000..=0x00F { // expands to structs Pin000, ..., Pin009, Pin00A, ..., Pin00F struct Pin~P; }); ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. seq-macro-0.3.5/src/lib.rs000064400000000000000000000266321046102023000134340ustar 00000000000000//! [![github]](https://github.com/dtolnay/seq-macro) [![crates-io]](https://crates.io/crates/seq-macro) [![docs-rs]](https://docs.rs/seq-macro) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! # Imagine for-loops in a macro //! //! This crate provides a `seq!` macro to repeat a fragment of source code and //! substitute into each repetition a sequential numeric counter. //! //! ``` //! use seq_macro::seq; //! //! fn main() { //! let tuple = (1000, 100, 10); //! let mut sum = 0; //! //! // Expands to: //! // //! // sum += tuple.0; //! // sum += tuple.1; //! // sum += tuple.2; //! // //! // This cannot be written using an ordinary for-loop because elements of //! // a tuple can only be accessed by their integer literal index, not by a //! // variable. //! seq!(N in 0..=2 { //! sum += tuple.N; //! }); //! //! assert_eq!(sum, 1110); //! } //! ``` //! //! - If the input tokens contain a section surrounded by `#(` ... `)*` then //! only that part is repeated. //! //! - The numeric counter can be pasted onto the end of some prefix to form //! sequential identifiers. //! //! ``` //! use seq_macro::seq; //! //! seq!(N in 64..=127 { //! #[derive(Debug)] //! enum Demo { //! // Expands to Variant64, Variant65, ... //! ##( //! Variant~N, //! )* //! } //! }); //! //! fn main() { //! assert_eq!("Variant99", format!("{:?}", Demo::Variant99)); //! } //! ``` //! //! - Byte and character ranges are supported: `b'a'..=b'z'`, `'a'..='z'`. //! //! - If the range bounds are written in binary, octal, hex, or with zero //! padding, those features are preserved in any generated tokens. //! //! ``` //! use seq_macro::seq; //! //! seq!(P in 0x000..=0x00F { //! // expands to structs Pin000, ..., Pin009, Pin00A, ..., Pin00F //! struct Pin~P; //! }); //! ``` #![doc(html_root_url = "https://docs.rs/seq-macro/0.3.5")] #![allow( clippy::cast_lossless, clippy::cast_possible_truncation, clippy::derive_partial_eq_without_eq, clippy::let_underscore_untyped, clippy::needless_doctest_main, clippy::single_match_else, clippy::wildcard_imports )] mod parse; use crate::parse::*; use proc_macro::{Delimiter, Group, Ident, Literal, Span, TokenStream, TokenTree}; use std::char; use std::iter::{self, FromIterator}; #[proc_macro] pub fn seq(input: TokenStream) -> TokenStream { match seq_impl(input) { Ok(expanded) => expanded, Err(error) => error.into_compile_error(), } } struct Range { begin: u64, end: u64, inclusive: bool, kind: Kind, suffix: String, width: usize, radix: Radix, } struct Value { int: u64, kind: Kind, suffix: String, width: usize, radix: Radix, span: Span, } struct Splice<'a> { int: u64, kind: Kind, suffix: &'a str, width: usize, radix: Radix, } #[derive(Copy, Clone, PartialEq)] enum Kind { Int, Byte, Char, } #[derive(Copy, Clone, PartialEq)] enum Radix { Binary, Octal, Decimal, LowerHex, UpperHex, } impl<'a> IntoIterator for &'a Range { type Item = Splice<'a>; type IntoIter = Box> + 'a>; fn into_iter(self) -> Self::IntoIter { let splice = move |int| Splice { int, kind: self.kind, suffix: &self.suffix, width: self.width, radix: self.radix, }; match self.kind { Kind::Int | Kind::Byte => { if self.inclusive { Box::new((self.begin..=self.end).map(splice)) } else { Box::new((self.begin..self.end).map(splice)) } } Kind::Char => { let begin = char::from_u32(self.begin as u32).unwrap(); let end = char::from_u32(self.end as u32).unwrap(); let int = |ch| u64::from(u32::from(ch)); if self.inclusive { Box::new((begin..=end).map(int).map(splice)) } else { Box::new((begin..end).map(int).map(splice)) } } } } } fn seq_impl(input: TokenStream) -> Result { let mut iter = input.into_iter(); let var = require_ident(&mut iter)?; require_keyword(&mut iter, "in")?; let begin = require_value(&mut iter)?; require_punct(&mut iter, '.')?; require_punct(&mut iter, '.')?; let inclusive = require_if_punct(&mut iter, '=')?; let end = require_value(&mut iter)?; let body = require_braces(&mut iter)?; require_end(&mut iter)?; let range = validate_range(begin, end, inclusive)?; let mut found_repetition = false; let expanded = expand_repetitions(&var, &range, body.clone(), &mut found_repetition); if found_repetition { Ok(expanded) } else { // If no `#(...)*`, repeat the entire body. Ok(repeat(&var, &range, &body)) } } fn repeat(var: &Ident, range: &Range, body: &TokenStream) -> TokenStream { let mut repeated = TokenStream::new(); for value in range { repeated.extend(substitute_value(var, &value, body.clone())); } repeated } fn substitute_value(var: &Ident, splice: &Splice, body: TokenStream) -> TokenStream { let mut tokens = Vec::from_iter(body); let mut i = 0; while i < tokens.len() { // Substitute our variable by itself, e.g. `N`. let replace = match &tokens[i] { TokenTree::Ident(ident) => ident.to_string() == var.to_string(), _ => false, }; if replace { let original_span = tokens[i].span(); let mut literal = splice.literal(); literal.set_span(original_span); tokens[i] = TokenTree::Literal(literal); i += 1; continue; } // Substitute our variable concatenated onto some prefix, `Prefix~N`. if i + 3 <= tokens.len() { let prefix = match &tokens[i..i + 3] { [first, TokenTree::Punct(tilde), TokenTree::Ident(ident)] if tilde.as_char() == '~' && ident.to_string() == var.to_string() => { match first { TokenTree::Ident(ident) => Some(ident.clone()), TokenTree::Group(group) => { let mut iter = group.stream().into_iter().fuse(); match (iter.next(), iter.next()) { (Some(TokenTree::Ident(ident)), None) => Some(ident), _ => None, } } _ => None, } } _ => None, }; if let Some(prefix) = prefix { let number = match splice.kind { Kind::Int => match splice.radix { Radix::Binary => format!("{0:01$b}", splice.int, splice.width), Radix::Octal => format!("{0:01$o}", splice.int, splice.width), Radix::Decimal => format!("{0:01$}", splice.int, splice.width), Radix::LowerHex => format!("{0:01$x}", splice.int, splice.width), Radix::UpperHex => format!("{0:01$X}", splice.int, splice.width), }, Kind::Byte | Kind::Char => { char::from_u32(splice.int as u32).unwrap().to_string() } }; let concat = format!("{}{}", prefix, number); let ident = Ident::new(&concat, prefix.span()); tokens.splice(i..i + 3, iter::once(TokenTree::Ident(ident))); i += 1; continue; } } // Recursively substitute content nested in a group. if let TokenTree::Group(group) = &mut tokens[i] { let original_span = group.span(); let content = substitute_value(var, splice, group.stream()); *group = Group::new(group.delimiter(), content); group.set_span(original_span); } i += 1; } TokenStream::from_iter(tokens) } fn enter_repetition(tokens: &[TokenTree]) -> Option { assert!(tokens.len() == 3); match &tokens[0] { TokenTree::Punct(punct) if punct.as_char() == '#' => {} _ => return None, } match &tokens[2] { TokenTree::Punct(punct) if punct.as_char() == '*' => {} _ => return None, } match &tokens[1] { TokenTree::Group(group) if group.delimiter() == Delimiter::Parenthesis => { Some(group.stream()) } _ => None, } } fn expand_repetitions( var: &Ident, range: &Range, body: TokenStream, found_repetition: &mut bool, ) -> TokenStream { let mut tokens = Vec::from_iter(body); // Look for `#(...)*`. let mut i = 0; while i < tokens.len() { if let TokenTree::Group(group) = &mut tokens[i] { let content = expand_repetitions(var, range, group.stream(), found_repetition); let original_span = group.span(); *group = Group::new(group.delimiter(), content); group.set_span(original_span); i += 1; continue; } if i + 3 > tokens.len() { i += 1; continue; } let template = match enter_repetition(&tokens[i..i + 3]) { Some(template) => template, None => { i += 1; continue; } }; *found_repetition = true; let mut repeated = Vec::new(); for value in range { repeated.extend(substitute_value(var, &value, template.clone())); } let repeated_len = repeated.len(); tokens.splice(i..i + 3, repeated); i += repeated_len; } TokenStream::from_iter(tokens) } impl Splice<'_> { fn literal(&self) -> Literal { match self.kind { Kind::Int | Kind::Byte => { let repr = match self.radix { Radix::Binary => format!("0b{0:02$b}{1}", self.int, self.suffix, self.width), Radix::Octal => format!("0o{0:02$o}{1}", self.int, self.suffix, self.width), Radix::Decimal => format!("{0:02$}{1}", self.int, self.suffix, self.width), Radix::LowerHex => format!("0x{0:02$x}{1}", self.int, self.suffix, self.width), Radix::UpperHex => format!("0x{0:02$X}{1}", self.int, self.suffix, self.width), }; let tokens = repr.parse::().unwrap(); let mut iter = tokens.into_iter(); let literal = match iter.next() { Some(TokenTree::Literal(literal)) => literal, _ => unreachable!(), }; assert!(iter.next().is_none()); literal } Kind::Char => { let ch = char::from_u32(self.int as u32).unwrap(); Literal::character(ch) } } } } seq-macro-0.3.5/src/parse.rs000064400000000000000000000177421046102023000140020ustar 00000000000000use crate::{Kind, Radix, Range, Value}; use proc_macro::token_stream::IntoIter as TokenIter; use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use std::borrow::Borrow; use std::cmp; use std::fmt::Display; use std::iter::FromIterator; pub(crate) struct SyntaxError { message: String, span: Span, } impl SyntaxError { pub(crate) fn into_compile_error(self) -> TokenStream { // compile_error! { $message } TokenStream::from_iter(vec![ TokenTree::Ident(Ident::new("compile_error", self.span)), TokenTree::Punct({ let mut punct = Punct::new('!', Spacing::Alone); punct.set_span(self.span); punct }), TokenTree::Group({ let mut group = Group::new(Delimiter::Brace, { TokenStream::from_iter(vec![TokenTree::Literal({ let mut string = Literal::string(&self.message); string.set_span(self.span); string })]) }); group.set_span(self.span); group }), ]) } } fn next_token(iter: &mut TokenIter) -> Result { iter.next().ok_or_else(|| SyntaxError { message: "unexpected end of input".to_owned(), span: Span::call_site(), }) } fn syntax, M: Display>(token: T, message: M) -> SyntaxError { SyntaxError { message: message.to_string(), span: token.borrow().span(), } } pub(crate) fn require_ident(iter: &mut TokenIter) -> Result { match next_token(iter)? { TokenTree::Ident(ident) => Ok(ident), other => Err(syntax(other, "expected ident")), } } pub(crate) fn require_keyword(iter: &mut TokenIter, keyword: &str) -> Result<(), SyntaxError> { let token = next_token(iter)?; if let TokenTree::Ident(ident) = &token { if ident.to_string() == keyword { return Ok(()); } } Err(syntax(token, format!("expected `{}`", keyword))) } pub(crate) fn require_value(iter: &mut TokenIter) -> Result { let mut token = next_token(iter)?; loop { match token { TokenTree::Group(group) => { let delimiter = group.delimiter(); let mut stream = group.stream().into_iter(); token = TokenTree::Group(group); if delimiter != Delimiter::None { break; } let first = match stream.next() { Some(first) => first, None => break, }; match stream.next() { Some(_) => break, None => token = first, } } TokenTree::Literal(lit) => { return parse_literal(&lit).ok_or_else(|| { let token = TokenTree::Literal(lit); syntax(token, "expected unsuffixed integer literal") }); } _ => break, } } Err(syntax(token, "expected integer")) } pub(crate) fn require_if_punct(iter: &mut TokenIter, ch: char) -> Result { let present = match iter.clone().next() { Some(TokenTree::Punct(_)) => { require_punct(iter, ch)?; true } _ => false, }; Ok(present) } pub(crate) fn require_punct(iter: &mut TokenIter, ch: char) -> Result<(), SyntaxError> { let token = next_token(iter)?; if let TokenTree::Punct(punct) = &token { if punct.as_char() == ch { return Ok(()); } } Err(syntax(token, format!("expected `{}`", ch))) } pub(crate) fn require_braces(iter: &mut TokenIter) -> Result { let token = next_token(iter)?; if let TokenTree::Group(group) = &token { if group.delimiter() == Delimiter::Brace { return Ok(group.stream()); } } Err(syntax(token, "expected curly braces")) } pub(crate) fn require_end(iter: &mut TokenIter) -> Result<(), SyntaxError> { match iter.next() { Some(token) => Err(syntax(token, "unexpected token")), None => Ok(()), } } pub(crate) fn validate_range( begin: Value, end: Value, inclusive: bool, ) -> Result { let kind = if begin.kind == end.kind { begin.kind } else { let expected = match begin.kind { Kind::Int => "integer", Kind::Byte => "byte", Kind::Char => "character", }; return Err(SyntaxError { message: format!("expected {} literal", expected), span: end.span, }); }; let suffix = if begin.suffix.is_empty() { end.suffix } else if end.suffix.is_empty() || begin.suffix == end.suffix { begin.suffix } else { return Err(SyntaxError { message: format!("expected suffix `{}`", begin.suffix), span: end.span, }); }; let radix = if begin.radix == end.radix { begin.radix } else if begin.radix == Radix::LowerHex && end.radix == Radix::UpperHex || begin.radix == Radix::UpperHex && end.radix == Radix::LowerHex { Radix::UpperHex } else { let expected = match begin.radix { Radix::Binary => "binary", Radix::Octal => "octal", Radix::Decimal => "base 10", Radix::LowerHex | Radix::UpperHex => "hexadecimal", }; return Err(SyntaxError { message: format!("expected {} literal", expected), span: end.span, }); }; Ok(Range { begin: begin.int, end: end.int, inclusive, kind, suffix, width: cmp::min(begin.width, end.width), radix, }) } fn parse_literal(lit: &Literal) -> Option { let span = lit.span(); let repr = lit.to_string(); assert!(!repr.starts_with('_')); if repr.starts_with("b'") && repr.ends_with('\'') && repr.len() == 4 { return Some(Value { int: repr.as_bytes()[2] as u64, kind: Kind::Byte, suffix: String::new(), width: 0, radix: Radix::Decimal, span, }); } if repr.starts_with('\'') && repr.ends_with('\'') && repr.chars().count() == 3 { return Some(Value { int: repr[1..].chars().next().unwrap() as u64, kind: Kind::Char, suffix: String::new(), width: 0, radix: Radix::Decimal, span, }); } let (mut radix, radix_n) = if repr.starts_with("0b") { (Radix::Binary, 2) } else if repr.starts_with("0o") { (Radix::Octal, 8) } else if repr.starts_with("0x") { (Radix::LowerHex, 16) } else if repr.starts_with("0X") { (Radix::UpperHex, 16) } else { (Radix::Decimal, 10) }; let mut iter = repr.char_indices(); let mut digits = String::new(); let mut suffix = String::new(); if radix != Radix::Decimal { let _ = iter.nth(1); } for (i, ch) in iter { match ch { '_' => continue, '0'..='9' => digits.push(ch), 'A'..='F' if radix == Radix::LowerHex => { digits.push(ch); radix = Radix::UpperHex; } 'a'..='f' | 'A'..='F' if radix_n == 16 => digits.push(ch), '.' => return None, _ => { if digits.is_empty() { return None; } suffix = repr; suffix.replace_range(..i, ""); break; } } } let int = u64::from_str_radix(&digits, radix_n).ok()?; let kind = Kind::Int; let width = digits.len(); Some(Value { int, kind, suffix, width, radix, span, }) } seq-macro-0.3.5/tests/compiletest.rs000064400000000000000000000002461046102023000155620ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[cfg_attr(miri, ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } seq-macro-0.3.5/tests/test.rs000064400000000000000000000131421046102023000142100ustar 00000000000000#![allow( clippy::derive_partial_eq_without_eq, clippy::identity_op, clippy::let_underscore_untyped, clippy::shadow_unrelated )] use seq_macro::seq; seq!(N in 0..8 { // nothing }); #[test] fn test_nothing() { macro_rules! expand_to_nothing { ($arg:literal) => { // nothing }; } seq!(N in 0..4 { expand_to_nothing!(N); }); } #[test] fn test_fn() { seq!(N in 1..4 { fn f~N () -> u64 { N * 2 } }); // This f0 is written separately to detect whether seq correctly starts with // the first iteration at N=1 as specified in the invocation. If the macro // incorrectly started at N=0, the first generated function would conflict // with this one and the program would not compile. fn f0() -> u64 { 100 } let sum = f0() + f1() + f2() + f3(); assert_eq!(sum, 100 + 2 + 4 + 6); } #[test] fn test_stringify() { let strings = seq!(N in 9..12 { [ #( stringify!(N), )* ] }); assert_eq!(strings, ["9", "10", "11"]); } #[test] fn test_underscores() { let n = seq!(N in 100_000..100_001 { N }); assert_eq!(100_000, n); } #[test] fn test_suffixed() { let n = seq!(N in 0..1u16 { stringify!(N) }); assert_eq!(n, "0u16"); } #[test] fn test_padding() { seq!(N in 098..=100 { fn e~N() -> &'static str { stringify!(N) } }); let strings = [e098(), e099(), e100()]; assert_eq!(strings, ["098", "099", "100"]); } #[test] fn test_byte() { seq!(c in b'x'..=b'z' { fn get_~c() -> u8 { c } }); let bytes = [get_x(), get_y(), get_z()]; assert_eq!(bytes, *b"xyz"); } #[test] fn test_char() { seq!(ch in 'x'..='z' { fn get_~ch() -> char { ch } }); let chars = [get_x(), get_y(), get_z()]; assert_eq!(chars, ['x', 'y', 'z']); } #[test] fn test_binary() { let s = seq!(B in 0b00..=0b11 { stringify!(#(B)*) }); let expected = "0b00 0b01 0b10 0b11"; assert_eq!(expected, s); } #[test] fn test_octal() { let s = seq!(O in 0o6..0o12 { stringify!(#(O)*) }); let expected = "0o6 0o7 0o10 0o11"; assert_eq!(expected, s); } #[test] fn test_hex() { let s = seq!(X in 0x08..0x0c { stringify!(#(X)*) }); let expected = "0x08 0x09 0x0a 0x0b"; assert_eq!(expected, s); let s = seq!(X in 0x08..0x0C { stringify!(#(X)*) }); let expected = "0x08 0x09 0x0A 0x0B"; assert_eq!(expected, s); let s = seq!(X in 0X09..0X10 { stringify!(#(X)*) }); let expected = "0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F"; assert_eq!(expected, s); } #[test] fn test_radix_concat() { seq!(B in 0b011..0b101 { struct S~B; }); seq!(O in 0o007..0o011 { struct S~O; }); seq!(X in 0x00a..0x00c { struct S~X; }); seq!(X in 0x00C..0x00E { struct S~X; }); let _ = (S011, S100, S007, S010, S00a, S00b, S00C, S00D); } #[test] fn test_ident() { macro_rules! create { ($prefix:ident) => { seq!(N in 0..1 { struct $prefix~N; }); }; } create!(Pin); let _ = Pin0; } pub mod test_enum { use seq_macro::seq; seq!(N in 0..16 { #[derive(Copy, Clone, PartialEq, Debug)] pub enum Interrupt { #( Irq~N, )* } }); #[test] fn test() { let interrupt = Interrupt::Irq8; assert_eq!(interrupt as u8, 8); assert_eq!(interrupt, Interrupt::Irq8); } } pub mod test_inclusive { use seq_macro::seq; seq!(N in 16..=20 { pub enum E { #( Variant~N, )* } }); #[test] fn test() { let e = E::Variant16; let desc = match e { E::Variant16 => "min", E::Variant17 | E::Variant18 | E::Variant19 => "in between", E::Variant20 => "max", }; assert_eq!(desc, "min"); } } #[test] fn test_array() { const PROCS: [Proc; 256] = { seq!(N in 0..256 { [ #( Proc::new(N), )* ] }) }; struct Proc { id: usize, } impl Proc { const fn new(id: usize) -> Self { Proc { id } } } assert_eq!(PROCS[32].id, 32); } pub mod test_group { use seq_macro::seq; // Source of truth. Call a given macro passing nproc as argument. macro_rules! pass_nproc { ($mac:ident) => { $mac! { 256 } }; } macro_rules! literal_identity_macro { ($nproc:literal) => { $nproc }; } const NPROC: usize = pass_nproc!(literal_identity_macro); pub struct Proc; impl Proc { const fn new() -> Self { Proc } } pub struct Mutex(T); impl Mutex { const fn new(_name: &'static str, value: T) -> Self { Mutex(value) } } macro_rules! make_procs_array { ($nproc:literal) => { seq!(N in 0..$nproc { [#(Proc::new(),)*] }) } } pub static PROCS: Mutex<[Proc; NPROC]> = Mutex::new("procs", pass_nproc!(make_procs_array)); } #[test] fn test_nested() { let mut vec = Vec::new(); macro_rules! some_macro { ($($t:ident,)*) => { vec.push(stringify!($($t)*)); }; } seq!(I in 1..=3 { #( seq!(J in 1..=I { some_macro!( #(T~J,)* ); }); )* }); assert_eq!(vec, ["T1", "T1 T2", "T1 T2 T3"]); } seq-macro-0.3.5/tests/ui/compile-error-span.rs000064400000000000000000000001651046102023000173650ustar 00000000000000use seq_macro::seq; seq!(N in 0..4 { compile_error!(concat!("error number ", stringify!(N))); }); fn main() {} seq-macro-0.3.5/tests/ui/compile-error-span.stderr000064400000000000000000000014171046102023000202450ustar 00000000000000error: error number 0 --> tests/ui/compile-error-span.rs:4:5 | 4 | compile_error!(concat!("error number ", stringify!(N))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: error number 1 --> tests/ui/compile-error-span.rs:4:5 | 4 | compile_error!(concat!("error number ", stringify!(N))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: error number 2 --> tests/ui/compile-error-span.rs:4:5 | 4 | compile_error!(concat!("error number ", stringify!(N))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: error number 3 --> tests/ui/compile-error-span.rs:4:5 | 4 | compile_error!(concat!("error number ", stringify!(N))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ seq-macro-0.3.5/tests/ui/ident-span.rs000064400000000000000000000001331046102023000157040ustar 00000000000000use seq_macro::seq; seq!(N in 0..1 { fn main() { let _ = Missing~N; } }); seq-macro-0.3.5/tests/ui/ident-span.stderr000064400000000000000000000002611046102023000165650ustar 00000000000000error[E0425]: cannot find value `Missing0` in this scope --> tests/ui/ident-span.rs:5:17 | 5 | let _ = Missing~N; | ^^^^^^^ not found in this scope seq-macro-0.3.5/tests/ui/kind-mismatch.rs000064400000000000000000000000741046102023000163760ustar 00000000000000use seq_macro::seq; seq!(N in 'a'..b'z' {}); fn main() {} seq-macro-0.3.5/tests/ui/kind-mismatch.stderr000064400000000000000000000001771046102023000172610ustar 00000000000000error: expected character literal --> tests/ui/kind-mismatch.rs:3:16 | 3 | seq!(N in 'a'..b'z' {}); | ^^^^ seq-macro-0.3.5/tests/ui/suffix-mismatch.rs000064400000000000000000000000741046102023000167550ustar 00000000000000use seq_macro::seq; seq!(N in 0u8..1u16 {}); fn main() {} seq-macro-0.3.5/tests/ui/suffix-mismatch.stderr000064400000000000000000000001731046102023000176340ustar 00000000000000error: expected suffix `u8` --> tests/ui/suffix-mismatch.rs:3:16 | 3 | seq!(N in 0u8..1u16 {}); | ^^^^