├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── lib.rs └── parse.rs └── tests ├── compiletest.rs ├── test.rs └── ui ├── compile-error-span.rs ├── compile-error-span.stderr ├── ident-span.rs ├── ident-span.stderr ├── kind-mismatch.rs ├── kind-mismatch.stderr ├── suffix-mismatch.rs └── suffix-mismatch.stderr /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: dtolnay 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | schedule: [cron: "40 1 * * *"] 8 | 9 | permissions: 10 | contents: read 11 | 12 | env: 13 | RUSTFLAGS: -Dwarnings 14 | 15 | jobs: 16 | pre_ci: 17 | uses: dtolnay/.github/.github/workflows/pre_ci.yml@master 18 | 19 | test: 20 | name: Rust ${{matrix.rust}} 21 | needs: pre_ci 22 | if: needs.pre_ci.outputs.continue 23 | runs-on: ubuntu-latest 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | rust: [nightly, beta, stable, 1.56.0] 28 | timeout-minutes: 45 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: dtolnay/rust-toolchain@master 32 | with: 33 | toolchain: ${{matrix.rust}} 34 | - name: Enable type layout randomization 35 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 36 | if: matrix.rust == 'nightly' 37 | - run: cargo test 38 | - uses: actions/upload-artifact@v4 39 | if: matrix.rust == 'nightly' && always() 40 | with: 41 | name: Cargo.lock 42 | path: Cargo.lock 43 | continue-on-error: true 44 | 45 | msrv: 46 | name: Rust 1.46.0 47 | needs: pre_ci 48 | if: needs.pre_ci.outputs.continue 49 | runs-on: ubuntu-latest 50 | timeout-minutes: 45 51 | steps: 52 | - uses: actions/checkout@v4 53 | - uses: dtolnay/rust-toolchain@1.46.0 54 | - run: cargo check 55 | 56 | doc: 57 | name: Documentation 58 | needs: pre_ci 59 | if: needs.pre_ci.outputs.continue 60 | runs-on: ubuntu-latest 61 | timeout-minutes: 45 62 | env: 63 | RUSTDOCFLAGS: -Dwarnings 64 | steps: 65 | - uses: actions/checkout@v4 66 | - uses: dtolnay/rust-toolchain@nightly 67 | - uses: dtolnay/install@cargo-docs-rs 68 | - run: cargo docs-rs 69 | 70 | clippy: 71 | name: Clippy 72 | runs-on: ubuntu-latest 73 | if: github.event_name != 'pull_request' 74 | timeout-minutes: 45 75 | steps: 76 | - uses: actions/checkout@v4 77 | - uses: dtolnay/rust-toolchain@clippy 78 | - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic 79 | 80 | miri: 81 | name: Miri 82 | needs: pre_ci 83 | if: needs.pre_ci.outputs.continue 84 | runs-on: ubuntu-latest 85 | timeout-minutes: 45 86 | steps: 87 | - uses: actions/checkout@v4 88 | - uses: dtolnay/rust-toolchain@master 89 | with: 90 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 91 | components: miri, rust-src 92 | - run: cargo miri setup 93 | - run: cargo miri test 94 | env: 95 | MIRIFLAGS: -Zmiri-strict-provenance 96 | 97 | outdated: 98 | name: Outdated 99 | runs-on: ubuntu-latest 100 | if: github.event_name != 'pull_request' 101 | timeout-minutes: 45 102 | steps: 103 | - uses: actions/checkout@v4 104 | - uses: dtolnay/rust-toolchain@stable 105 | - uses: dtolnay/install@cargo-outdated 106 | - run: cargo outdated --workspace --exit-code 1 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "seq-macro" 3 | version = "0.3.6" 4 | authors = ["David Tolnay "] 5 | categories = ["development-tools", "no-std", "no-std::no-alloc"] 6 | description = "Macro to repeat sequentially indexed copies of a fragment of code." 7 | documentation = "https://docs.rs/seq-macro" 8 | edition = "2018" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/dtolnay/seq-macro" 11 | rust-version = "1.45" 12 | 13 | [lib] 14 | proc-macro = true 15 | 16 | [dev-dependencies] 17 | rustversion = "1.0" 18 | trybuild = { version = "1.0.49", features = ["diff"] } 19 | 20 | [package.metadata.docs.rs] 21 | targets = ["x86_64-unknown-linux-gnu"] 22 | rustdoc-args = [ 23 | "--generate-link-to-definition", 24 | "--extern-html-root-url=core=https://doc.rust-lang.org", 25 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 26 | "--extern-html-root-url=std=https://doc.rust-lang.org", 27 | "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", 28 | ] 29 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | `seq!` 2 | ====== 3 | 4 | [github](https://github.com/dtolnay/seq-macro) 5 | [crates.io](https://crates.io/crates/seq-macro) 6 | [docs.rs](https://docs.rs/seq-macro) 7 | [build status](https://github.com/dtolnay/seq-macro/actions?query=branch%3Amaster) 8 | 9 | A `seq!` macro to repeat a fragment of source code and substitute into each 10 | repetition a sequential numeric counter. 11 | 12 | ```toml 13 | [dependencies] 14 | seq-macro = "0.3" 15 | ``` 16 | 17 | ```rust 18 | use seq_macro::seq; 19 | 20 | fn main() { 21 | let tuple = (1000, 100, 10); 22 | let mut sum = 0; 23 | 24 | // Expands to: 25 | // 26 | // sum += tuple.0; 27 | // sum += tuple.1; 28 | // sum += tuple.2; 29 | // 30 | // This cannot be written using an ordinary for-loop because elements of 31 | // a tuple can only be accessed by their integer literal index, not by a 32 | // variable. 33 | seq!(N in 0..=2 { 34 | sum += tuple.N; 35 | }); 36 | 37 | assert_eq!(sum, 1110); 38 | } 39 | ``` 40 | 41 | - If the input tokens contain a section surrounded by `#(` ... `)*` then only 42 | that part is repeated. 43 | 44 | - The numeric counter can be pasted onto the end of some prefix to form 45 | sequential identifiers. 46 | 47 | ```rust 48 | use seq_macro::seq; 49 | 50 | seq!(N in 64..=127 { 51 | #[derive(Debug)] 52 | enum Demo { 53 | // Expands to Variant64, Variant65, ... 54 | #( 55 | Variant~N, 56 | )* 57 | } 58 | }); 59 | 60 | fn main() { 61 | assert_eq!("Variant99", format!("{:?}", Demo::Variant99)); 62 | } 63 | ``` 64 | 65 | - Byte and character ranges are supported: `b'a'..=b'z'`, `'a'..='z'`. 66 | 67 | - If the range bounds are written in binary, octal, hex, or with zero padding, 68 | those features are preserved in any generated tokens. 69 | 70 | ```rust 71 | use seq_macro::seq; 72 | 73 | seq!(P in 0x000..=0x00F { 74 | // expands to structs Pin000, ..., Pin009, Pin00A, ..., Pin00F 75 | struct Pin~P; 76 | }); 77 | ``` 78 | 79 |
80 | 81 | #### License 82 | 83 | 84 | Licensed under either of Apache License, Version 85 | 2.0 or MIT license at your option. 86 | 87 | 88 |
89 | 90 | 91 | Unless you explicitly state otherwise, any contribution intentionally submitted 92 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 93 | be dual licensed as above, without any additional terms or conditions. 94 | 95 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/seq-macro) [![crates-io]](https://crates.io/crates/seq-macro) [![docs-rs]](https://docs.rs/seq-macro) 2 | //! 3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github 4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust 5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs 6 | //! 7 | //!
8 | //! 9 | //! # Imagine for-loops in a macro 10 | //! 11 | //! This crate provides a `seq!` macro to repeat a fragment of source code and 12 | //! substitute into each repetition a sequential numeric counter. 13 | //! 14 | //! ``` 15 | //! use seq_macro::seq; 16 | //! 17 | //! fn main() { 18 | //! let tuple = (1000, 100, 10); 19 | //! let mut sum = 0; 20 | //! 21 | //! // Expands to: 22 | //! // 23 | //! // sum += tuple.0; 24 | //! // sum += tuple.1; 25 | //! // sum += tuple.2; 26 | //! // 27 | //! // This cannot be written using an ordinary for-loop because elements of 28 | //! // a tuple can only be accessed by their integer literal index, not by a 29 | //! // variable. 30 | //! seq!(N in 0..=2 { 31 | //! sum += tuple.N; 32 | //! }); 33 | //! 34 | //! assert_eq!(sum, 1110); 35 | //! } 36 | //! ``` 37 | //! 38 | //! - If the input tokens contain a section surrounded by `#(` ... `)*` then 39 | //! only that part is repeated. 40 | //! 41 | //! - The numeric counter can be pasted onto the end of some prefix to form 42 | //! sequential identifiers. 43 | //! 44 | //! ``` 45 | //! use seq_macro::seq; 46 | //! 47 | //! seq!(N in 64..=127 { 48 | //! #[derive(Debug)] 49 | //! enum Demo { 50 | //! // Expands to Variant64, Variant65, ... 51 | //! ##( 52 | //! Variant~N, 53 | //! )* 54 | //! } 55 | //! }); 56 | //! 57 | //! fn main() { 58 | //! assert_eq!("Variant99", format!("{:?}", Demo::Variant99)); 59 | //! } 60 | //! ``` 61 | //! 62 | //! - Byte and character ranges are supported: `b'a'..=b'z'`, `'a'..='z'`. 63 | //! 64 | //! - If the range bounds are written in binary, octal, hex, or with zero 65 | //! padding, those features are preserved in any generated tokens. 66 | //! 67 | //! ``` 68 | //! use seq_macro::seq; 69 | //! 70 | //! seq!(P in 0x000..=0x00F { 71 | //! // expands to structs Pin000, ..., Pin009, Pin00A, ..., Pin00F 72 | //! struct Pin~P; 73 | //! }); 74 | //! ``` 75 | 76 | #![doc(html_root_url = "https://docs.rs/seq-macro/0.3.6")] 77 | #![allow( 78 | clippy::cast_lossless, 79 | clippy::cast_possible_truncation, 80 | clippy::derive_partial_eq_without_eq, 81 | clippy::into_iter_without_iter, 82 | clippy::let_underscore_untyped, 83 | clippy::needless_doctest_main, 84 | clippy::single_match_else, 85 | clippy::wildcard_imports 86 | )] 87 | 88 | mod parse; 89 | 90 | use crate::parse::*; 91 | use proc_macro::{Delimiter, Group, Ident, Literal, Span, TokenStream, TokenTree}; 92 | use std::char; 93 | use std::iter::{self, FromIterator}; 94 | 95 | #[proc_macro] 96 | pub fn seq(input: TokenStream) -> TokenStream { 97 | match seq_impl(input) { 98 | Ok(expanded) => expanded, 99 | Err(error) => error.into_compile_error(), 100 | } 101 | } 102 | 103 | struct Range { 104 | begin: u64, 105 | end: u64, 106 | inclusive: bool, 107 | kind: Kind, 108 | suffix: String, 109 | width: usize, 110 | radix: Radix, 111 | } 112 | 113 | struct Value { 114 | int: u64, 115 | kind: Kind, 116 | suffix: String, 117 | width: usize, 118 | radix: Radix, 119 | span: Span, 120 | } 121 | 122 | struct Splice<'a> { 123 | int: u64, 124 | kind: Kind, 125 | suffix: &'a str, 126 | width: usize, 127 | radix: Radix, 128 | } 129 | 130 | #[derive(Copy, Clone, PartialEq)] 131 | enum Kind { 132 | Int, 133 | Byte, 134 | Char, 135 | } 136 | 137 | #[derive(Copy, Clone, PartialEq)] 138 | enum Radix { 139 | Binary, 140 | Octal, 141 | Decimal, 142 | LowerHex, 143 | UpperHex, 144 | } 145 | 146 | impl<'a> IntoIterator for &'a Range { 147 | type Item = Splice<'a>; 148 | type IntoIter = Box> + 'a>; 149 | 150 | fn into_iter(self) -> Self::IntoIter { 151 | let splice = move |int| Splice { 152 | int, 153 | kind: self.kind, 154 | suffix: &self.suffix, 155 | width: self.width, 156 | radix: self.radix, 157 | }; 158 | match self.kind { 159 | Kind::Int | Kind::Byte => { 160 | if self.inclusive { 161 | Box::new((self.begin..=self.end).map(splice)) 162 | } else { 163 | Box::new((self.begin..self.end).map(splice)) 164 | } 165 | } 166 | Kind::Char => { 167 | let begin = char::from_u32(self.begin as u32).unwrap(); 168 | let end = char::from_u32(self.end as u32).unwrap(); 169 | let int = |ch| u64::from(u32::from(ch)); 170 | if self.inclusive { 171 | Box::new((begin..=end).map(int).map(splice)) 172 | } else { 173 | Box::new((begin..end).map(int).map(splice)) 174 | } 175 | } 176 | } 177 | } 178 | } 179 | 180 | fn seq_impl(input: TokenStream) -> Result { 181 | let mut iter = input.into_iter(); 182 | let var = require_ident(&mut iter)?; 183 | require_keyword(&mut iter, "in")?; 184 | let begin = require_value(&mut iter)?; 185 | require_punct(&mut iter, '.')?; 186 | require_punct(&mut iter, '.')?; 187 | let inclusive = require_if_punct(&mut iter, '=')?; 188 | let end = require_value(&mut iter)?; 189 | let body = require_braces(&mut iter)?; 190 | require_end(&mut iter)?; 191 | 192 | let range = validate_range(begin, end, inclusive)?; 193 | 194 | let mut found_repetition = false; 195 | let expanded = expand_repetitions(&var, &range, body.clone(), &mut found_repetition); 196 | if found_repetition { 197 | Ok(expanded) 198 | } else { 199 | // If no `#(...)*`, repeat the entire body. 200 | Ok(repeat(&var, &range, &body)) 201 | } 202 | } 203 | 204 | fn repeat(var: &Ident, range: &Range, body: &TokenStream) -> TokenStream { 205 | let mut repeated = TokenStream::new(); 206 | for value in range { 207 | repeated.extend(substitute_value(var, &value, body.clone())); 208 | } 209 | repeated 210 | } 211 | 212 | fn substitute_value(var: &Ident, splice: &Splice, body: TokenStream) -> TokenStream { 213 | let mut tokens = Vec::from_iter(body); 214 | 215 | let mut i = 0; 216 | while i < tokens.len() { 217 | // Substitute our variable by itself, e.g. `N`. 218 | let replace = match &tokens[i] { 219 | TokenTree::Ident(ident) => ident.to_string() == var.to_string(), 220 | _ => false, 221 | }; 222 | if replace { 223 | let original_span = tokens[i].span(); 224 | let mut literal = splice.literal(); 225 | literal.set_span(original_span); 226 | tokens[i] = TokenTree::Literal(literal); 227 | i += 1; 228 | continue; 229 | } 230 | 231 | // Substitute our variable concatenated onto some prefix, `Prefix~N`. 232 | if i + 3 <= tokens.len() { 233 | let prefix = match &tokens[i..i + 3] { 234 | [first, TokenTree::Punct(tilde), TokenTree::Ident(ident)] 235 | if tilde.as_char() == '~' && ident.to_string() == var.to_string() => 236 | { 237 | match first { 238 | TokenTree::Ident(ident) => Some(ident.clone()), 239 | TokenTree::Group(group) => { 240 | let mut iter = group.stream().into_iter().fuse(); 241 | match (iter.next(), iter.next()) { 242 | (Some(TokenTree::Ident(ident)), None) => Some(ident), 243 | _ => None, 244 | } 245 | } 246 | _ => None, 247 | } 248 | } 249 | _ => None, 250 | }; 251 | if let Some(prefix) = prefix { 252 | let number = match splice.kind { 253 | Kind::Int => match splice.radix { 254 | Radix::Binary => format!("{0:01$b}", splice.int, splice.width), 255 | Radix::Octal => format!("{0:01$o}", splice.int, splice.width), 256 | Radix::Decimal => format!("{0:01$}", splice.int, splice.width), 257 | Radix::LowerHex => format!("{0:01$x}", splice.int, splice.width), 258 | Radix::UpperHex => format!("{0:01$X}", splice.int, splice.width), 259 | }, 260 | Kind::Byte | Kind::Char => { 261 | char::from_u32(splice.int as u32).unwrap().to_string() 262 | } 263 | }; 264 | let concat = format!("{}{}", prefix, number); 265 | let ident = Ident::new(&concat, prefix.span()); 266 | tokens.splice(i..i + 3, iter::once(TokenTree::Ident(ident))); 267 | i += 1; 268 | continue; 269 | } 270 | } 271 | 272 | // Recursively substitute content nested in a group. 273 | if let TokenTree::Group(group) = &mut tokens[i] { 274 | let original_span = group.span(); 275 | let content = substitute_value(var, splice, group.stream()); 276 | *group = Group::new(group.delimiter(), content); 277 | group.set_span(original_span); 278 | } 279 | 280 | i += 1; 281 | } 282 | 283 | TokenStream::from_iter(tokens) 284 | } 285 | 286 | fn enter_repetition(tokens: &[TokenTree]) -> Option { 287 | assert!(tokens.len() == 3); 288 | match &tokens[0] { 289 | TokenTree::Punct(punct) if punct.as_char() == '#' => {} 290 | _ => return None, 291 | } 292 | match &tokens[2] { 293 | TokenTree::Punct(punct) if punct.as_char() == '*' => {} 294 | _ => return None, 295 | } 296 | match &tokens[1] { 297 | TokenTree::Group(group) if group.delimiter() == Delimiter::Parenthesis => { 298 | Some(group.stream()) 299 | } 300 | _ => None, 301 | } 302 | } 303 | 304 | fn expand_repetitions( 305 | var: &Ident, 306 | range: &Range, 307 | body: TokenStream, 308 | found_repetition: &mut bool, 309 | ) -> TokenStream { 310 | let mut tokens = Vec::from_iter(body); 311 | 312 | // Look for `#(...)*`. 313 | let mut i = 0; 314 | while i < tokens.len() { 315 | if let TokenTree::Group(group) = &mut tokens[i] { 316 | let content = expand_repetitions(var, range, group.stream(), found_repetition); 317 | let original_span = group.span(); 318 | *group = Group::new(group.delimiter(), content); 319 | group.set_span(original_span); 320 | i += 1; 321 | continue; 322 | } 323 | if i + 3 > tokens.len() { 324 | i += 1; 325 | continue; 326 | } 327 | let template = match enter_repetition(&tokens[i..i + 3]) { 328 | Some(template) => template, 329 | None => { 330 | i += 1; 331 | continue; 332 | } 333 | }; 334 | *found_repetition = true; 335 | let mut repeated = Vec::new(); 336 | for value in range { 337 | repeated.extend(substitute_value(var, &value, template.clone())); 338 | } 339 | let repeated_len = repeated.len(); 340 | tokens.splice(i..i + 3, repeated); 341 | i += repeated_len; 342 | } 343 | 344 | TokenStream::from_iter(tokens) 345 | } 346 | 347 | impl Splice<'_> { 348 | fn literal(&self) -> Literal { 349 | match self.kind { 350 | Kind::Int | Kind::Byte => { 351 | let repr = match self.radix { 352 | Radix::Binary => format!("0b{0:02$b}{1}", self.int, self.suffix, self.width), 353 | Radix::Octal => format!("0o{0:02$o}{1}", self.int, self.suffix, self.width), 354 | Radix::Decimal => format!("{0:02$}{1}", self.int, self.suffix, self.width), 355 | Radix::LowerHex => format!("0x{0:02$x}{1}", self.int, self.suffix, self.width), 356 | Radix::UpperHex => format!("0x{0:02$X}{1}", self.int, self.suffix, self.width), 357 | }; 358 | let tokens = repr.parse::().unwrap(); 359 | let mut iter = tokens.into_iter(); 360 | let literal = match iter.next() { 361 | Some(TokenTree::Literal(literal)) => literal, 362 | _ => unreachable!(), 363 | }; 364 | assert!(iter.next().is_none()); 365 | literal 366 | } 367 | Kind::Char => { 368 | let ch = char::from_u32(self.int as u32).unwrap(); 369 | Literal::character(ch) 370 | } 371 | } 372 | } 373 | } 374 | -------------------------------------------------------------------------------- /src/parse.rs: -------------------------------------------------------------------------------- 1 | use crate::{Kind, Radix, Range, Value}; 2 | use proc_macro::token_stream::IntoIter as TokenIter; 3 | use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 4 | use std::borrow::Borrow; 5 | use std::cmp; 6 | use std::fmt::Display; 7 | use std::iter::FromIterator; 8 | 9 | pub(crate) struct SyntaxError { 10 | message: String, 11 | span: Span, 12 | } 13 | 14 | impl SyntaxError { 15 | pub(crate) fn into_compile_error(self) -> TokenStream { 16 | // compile_error! { $message } 17 | TokenStream::from_iter(vec![ 18 | TokenTree::Ident(Ident::new("compile_error", self.span)), 19 | TokenTree::Punct({ 20 | let mut punct = Punct::new('!', Spacing::Alone); 21 | punct.set_span(self.span); 22 | punct 23 | }), 24 | TokenTree::Group({ 25 | let mut group = Group::new(Delimiter::Brace, { 26 | TokenStream::from_iter(vec![TokenTree::Literal({ 27 | let mut string = Literal::string(&self.message); 28 | string.set_span(self.span); 29 | string 30 | })]) 31 | }); 32 | group.set_span(self.span); 33 | group 34 | }), 35 | ]) 36 | } 37 | } 38 | 39 | fn next_token(iter: &mut TokenIter) -> Result { 40 | iter.next().ok_or_else(|| SyntaxError { 41 | message: "unexpected end of input".to_owned(), 42 | span: Span::call_site(), 43 | }) 44 | } 45 | 46 | fn syntax, M: Display>(token: T, message: M) -> SyntaxError { 47 | SyntaxError { 48 | message: message.to_string(), 49 | span: token.borrow().span(), 50 | } 51 | } 52 | 53 | pub(crate) fn require_ident(iter: &mut TokenIter) -> Result { 54 | match next_token(iter)? { 55 | TokenTree::Ident(ident) => Ok(ident), 56 | other => Err(syntax(other, "expected ident")), 57 | } 58 | } 59 | 60 | pub(crate) fn require_keyword(iter: &mut TokenIter, keyword: &str) -> Result<(), SyntaxError> { 61 | let token = next_token(iter)?; 62 | if let TokenTree::Ident(ident) = &token { 63 | if ident.to_string() == keyword { 64 | return Ok(()); 65 | } 66 | } 67 | Err(syntax(token, format!("expected `{}`", keyword))) 68 | } 69 | 70 | pub(crate) fn require_value(iter: &mut TokenIter) -> Result { 71 | let mut token = next_token(iter)?; 72 | 73 | loop { 74 | match token { 75 | TokenTree::Group(group) => { 76 | let delimiter = group.delimiter(); 77 | let mut stream = group.stream().into_iter(); 78 | token = TokenTree::Group(group); 79 | if delimiter != Delimiter::None { 80 | break; 81 | } 82 | let first = match stream.next() { 83 | Some(first) => first, 84 | None => break, 85 | }; 86 | match stream.next() { 87 | Some(_) => break, 88 | None => token = first, 89 | } 90 | } 91 | TokenTree::Literal(lit) => { 92 | return parse_literal(&lit).ok_or_else(|| { 93 | let token = TokenTree::Literal(lit); 94 | syntax(token, "expected unsuffixed integer literal") 95 | }); 96 | } 97 | _ => break, 98 | } 99 | } 100 | 101 | Err(syntax(token, "expected integer")) 102 | } 103 | 104 | pub(crate) fn require_if_punct(iter: &mut TokenIter, ch: char) -> Result { 105 | let present = match iter.clone().next() { 106 | Some(TokenTree::Punct(_)) => { 107 | require_punct(iter, ch)?; 108 | true 109 | } 110 | _ => false, 111 | }; 112 | Ok(present) 113 | } 114 | 115 | pub(crate) fn require_punct(iter: &mut TokenIter, ch: char) -> Result<(), SyntaxError> { 116 | let token = next_token(iter)?; 117 | if let TokenTree::Punct(punct) = &token { 118 | if punct.as_char() == ch { 119 | return Ok(()); 120 | } 121 | } 122 | Err(syntax(token, format!("expected `{}`", ch))) 123 | } 124 | 125 | pub(crate) fn require_braces(iter: &mut TokenIter) -> Result { 126 | let token = next_token(iter)?; 127 | if let TokenTree::Group(group) = &token { 128 | if group.delimiter() == Delimiter::Brace { 129 | return Ok(group.stream()); 130 | } 131 | } 132 | Err(syntax(token, "expected curly braces")) 133 | } 134 | 135 | pub(crate) fn require_end(iter: &mut TokenIter) -> Result<(), SyntaxError> { 136 | match iter.next() { 137 | Some(token) => Err(syntax(token, "unexpected token")), 138 | None => Ok(()), 139 | } 140 | } 141 | 142 | pub(crate) fn validate_range( 143 | begin: Value, 144 | end: Value, 145 | inclusive: bool, 146 | ) -> Result { 147 | let kind = if begin.kind == end.kind { 148 | begin.kind 149 | } else { 150 | let expected = match begin.kind { 151 | Kind::Int => "integer", 152 | Kind::Byte => "byte", 153 | Kind::Char => "character", 154 | }; 155 | return Err(SyntaxError { 156 | message: format!("expected {} literal", expected), 157 | span: end.span, 158 | }); 159 | }; 160 | 161 | let suffix = if begin.suffix.is_empty() { 162 | end.suffix 163 | } else if end.suffix.is_empty() || begin.suffix == end.suffix { 164 | begin.suffix 165 | } else { 166 | return Err(SyntaxError { 167 | message: format!("expected suffix `{}`", begin.suffix), 168 | span: end.span, 169 | }); 170 | }; 171 | 172 | let radix = if begin.radix == end.radix { 173 | begin.radix 174 | } else if begin.radix == Radix::LowerHex && end.radix == Radix::UpperHex 175 | || begin.radix == Radix::UpperHex && end.radix == Radix::LowerHex 176 | { 177 | Radix::UpperHex 178 | } else { 179 | let expected = match begin.radix { 180 | Radix::Binary => "binary", 181 | Radix::Octal => "octal", 182 | Radix::Decimal => "base 10", 183 | Radix::LowerHex | Radix::UpperHex => "hexadecimal", 184 | }; 185 | return Err(SyntaxError { 186 | message: format!("expected {} literal", expected), 187 | span: end.span, 188 | }); 189 | }; 190 | 191 | Ok(Range { 192 | begin: begin.int, 193 | end: end.int, 194 | inclusive, 195 | kind, 196 | suffix, 197 | width: cmp::min(begin.width, end.width), 198 | radix, 199 | }) 200 | } 201 | 202 | fn parse_literal(lit: &Literal) -> Option { 203 | let span = lit.span(); 204 | let repr = lit.to_string(); 205 | assert!(!repr.starts_with('_')); 206 | 207 | if repr.starts_with("b'") && repr.ends_with('\'') && repr.len() == 4 { 208 | return Some(Value { 209 | int: repr.as_bytes()[2] as u64, 210 | kind: Kind::Byte, 211 | suffix: String::new(), 212 | width: 0, 213 | radix: Radix::Decimal, 214 | span, 215 | }); 216 | } 217 | 218 | if repr.starts_with('\'') && repr.ends_with('\'') && repr.chars().count() == 3 { 219 | return Some(Value { 220 | int: repr[1..].chars().next().unwrap() as u64, 221 | kind: Kind::Char, 222 | suffix: String::new(), 223 | width: 0, 224 | radix: Radix::Decimal, 225 | span, 226 | }); 227 | } 228 | 229 | let (mut radix, radix_n) = if repr.starts_with("0b") { 230 | (Radix::Binary, 2) 231 | } else if repr.starts_with("0o") { 232 | (Radix::Octal, 8) 233 | } else if repr.starts_with("0x") { 234 | (Radix::LowerHex, 16) 235 | } else if repr.starts_with("0X") { 236 | (Radix::UpperHex, 16) 237 | } else { 238 | (Radix::Decimal, 10) 239 | }; 240 | 241 | let mut iter = repr.char_indices(); 242 | let mut digits = String::new(); 243 | let mut suffix = String::new(); 244 | 245 | if radix != Radix::Decimal { 246 | let _ = iter.nth(1); 247 | } 248 | 249 | for (i, ch) in iter { 250 | match ch { 251 | '_' => {} 252 | '0'..='9' => digits.push(ch), 253 | 'A'..='F' if radix == Radix::LowerHex => { 254 | digits.push(ch); 255 | radix = Radix::UpperHex; 256 | } 257 | 'a'..='f' | 'A'..='F' if radix_n == 16 => digits.push(ch), 258 | '.' => return None, 259 | _ => { 260 | if digits.is_empty() { 261 | return None; 262 | } 263 | suffix = repr; 264 | suffix.replace_range(..i, ""); 265 | break; 266 | } 267 | } 268 | } 269 | 270 | let int = u64::from_str_radix(&digits, radix_n).ok()?; 271 | let kind = Kind::Int; 272 | let width = digits.len(); 273 | Some(Value { 274 | int, 275 | kind, 276 | suffix, 277 | width, 278 | radix, 279 | span, 280 | }) 281 | } 282 | -------------------------------------------------------------------------------- /tests/compiletest.rs: -------------------------------------------------------------------------------- 1 | #[rustversion::attr(not(nightly), ignore = "requires nightly")] 2 | #[cfg_attr(miri, ignore = "incompatible with miri")] 3 | #[test] 4 | fn ui() { 5 | let t = trybuild::TestCases::new(); 6 | t.compile_fail("tests/ui/*.rs"); 7 | } 8 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | #![allow( 2 | clippy::derive_partial_eq_without_eq, 3 | clippy::identity_op, 4 | clippy::let_underscore_untyped, 5 | clippy::shadow_unrelated 6 | )] 7 | 8 | use seq_macro::seq; 9 | 10 | seq!(N in 0..8 { 11 | // nothing 12 | }); 13 | 14 | #[test] 15 | fn test_nothing() { 16 | macro_rules! expand_to_nothing { 17 | ($arg:literal) => { 18 | // nothing 19 | }; 20 | } 21 | 22 | seq!(N in 0..4 { 23 | expand_to_nothing!(N); 24 | }); 25 | } 26 | 27 | #[test] 28 | fn test_fn() { 29 | seq!(N in 1..4 { 30 | fn f~N () -> u64 { 31 | N * 2 32 | } 33 | }); 34 | 35 | // This f0 is written separately to detect whether seq correctly starts with 36 | // the first iteration at N=1 as specified in the invocation. If the macro 37 | // incorrectly started at N=0, the first generated function would conflict 38 | // with this one and the program would not compile. 39 | fn f0() -> u64 { 40 | 100 41 | } 42 | 43 | let sum = f0() + f1() + f2() + f3(); 44 | assert_eq!(sum, 100 + 2 + 4 + 6); 45 | } 46 | 47 | #[test] 48 | fn test_stringify() { 49 | let strings = seq!(N in 9..12 { 50 | [ 51 | #( 52 | stringify!(N), 53 | )* 54 | ] 55 | }); 56 | assert_eq!(strings, ["9", "10", "11"]); 57 | } 58 | 59 | #[test] 60 | fn test_underscores() { 61 | let n = seq!(N in 100_000..100_001 { N }); 62 | assert_eq!(100_000, n); 63 | } 64 | 65 | #[test] 66 | fn test_suffixed() { 67 | let n = seq!(N in 0..1u16 { stringify!(N) }); 68 | assert_eq!(n, "0u16"); 69 | } 70 | 71 | #[test] 72 | fn test_padding() { 73 | seq!(N in 098..=100 { 74 | fn e~N() -> &'static str { 75 | stringify!(N) 76 | } 77 | }); 78 | let strings = [e098(), e099(), e100()]; 79 | assert_eq!(strings, ["098", "099", "100"]); 80 | } 81 | 82 | #[test] 83 | fn test_byte() { 84 | seq!(c in b'x'..=b'z' { 85 | fn get_~c() -> u8 { 86 | c 87 | } 88 | }); 89 | let bytes = [get_x(), get_y(), get_z()]; 90 | assert_eq!(bytes, *b"xyz"); 91 | } 92 | 93 | #[test] 94 | fn test_char() { 95 | seq!(ch in 'x'..='z' { 96 | fn get_~ch() -> char { 97 | ch 98 | } 99 | }); 100 | let chars = [get_x(), get_y(), get_z()]; 101 | assert_eq!(chars, ['x', 'y', 'z']); 102 | } 103 | 104 | #[test] 105 | fn test_binary() { 106 | let s = seq!(B in 0b00..=0b11 { stringify!(#(B)*) }); 107 | let expected = "0b00 0b01 0b10 0b11"; 108 | assert_eq!(expected, s); 109 | } 110 | 111 | #[test] 112 | fn test_octal() { 113 | let s = seq!(O in 0o6..0o12 { stringify!(#(O)*) }); 114 | let expected = "0o6 0o7 0o10 0o11"; 115 | assert_eq!(expected, s); 116 | } 117 | 118 | #[test] 119 | fn test_hex() { 120 | let s = seq!(X in 0x08..0x0c { stringify!(#(X)*) }); 121 | let expected = "0x08 0x09 0x0a 0x0b"; 122 | assert_eq!(expected, s); 123 | 124 | let s = seq!(X in 0x08..0x0C { stringify!(#(X)*) }); 125 | let expected = "0x08 0x09 0x0A 0x0B"; 126 | assert_eq!(expected, s); 127 | 128 | let s = seq!(X in 0X09..0X10 { stringify!(#(X)*) }); 129 | let expected = "0x09 0x0A 0x0B 0x0C 0x0D 0x0E 0x0F"; 130 | assert_eq!(expected, s); 131 | } 132 | 133 | #[test] 134 | fn test_radix_concat() { 135 | seq!(B in 0b011..0b101 { struct S~B; }); 136 | seq!(O in 0o007..0o011 { struct S~O; }); 137 | seq!(X in 0x00a..0x00c { struct S~X; }); 138 | seq!(X in 0x00C..0x00E { struct S~X; }); 139 | let _ = (S011, S100, S007, S010, S00a, S00b, S00C, S00D); 140 | } 141 | 142 | #[test] 143 | fn test_ident() { 144 | macro_rules! create { 145 | ($prefix:ident) => { 146 | seq!(N in 0..1 { 147 | struct $prefix~N; 148 | }); 149 | }; 150 | } 151 | create!(Pin); 152 | let _ = Pin0; 153 | } 154 | 155 | pub mod test_enum { 156 | use seq_macro::seq; 157 | 158 | seq!(N in 0..16 { 159 | #[derive(Copy, Clone, PartialEq, Debug)] 160 | pub enum Interrupt { 161 | #( 162 | Irq~N, 163 | )* 164 | } 165 | }); 166 | 167 | #[test] 168 | fn test() { 169 | let interrupt = Interrupt::Irq8; 170 | assert_eq!(interrupt as u8, 8); 171 | assert_eq!(interrupt, Interrupt::Irq8); 172 | } 173 | } 174 | 175 | pub mod test_inclusive { 176 | use seq_macro::seq; 177 | 178 | seq!(N in 16..=20 { 179 | pub enum E { 180 | #( 181 | Variant~N, 182 | )* 183 | } 184 | }); 185 | 186 | #[test] 187 | fn test() { 188 | let e = E::Variant16; 189 | 190 | let desc = match e { 191 | E::Variant16 => "min", 192 | E::Variant17 | E::Variant18 | E::Variant19 => "in between", 193 | E::Variant20 => "max", 194 | }; 195 | 196 | assert_eq!(desc, "min"); 197 | } 198 | } 199 | 200 | #[test] 201 | fn test_array() { 202 | const PROCS: [Proc; 256] = { 203 | seq!(N in 0..256 { 204 | [ 205 | #( 206 | Proc::new(N), 207 | )* 208 | ] 209 | }) 210 | }; 211 | 212 | struct Proc { 213 | id: usize, 214 | } 215 | 216 | impl Proc { 217 | const fn new(id: usize) -> Self { 218 | Proc { id } 219 | } 220 | } 221 | 222 | assert_eq!(PROCS[32].id, 32); 223 | } 224 | 225 | pub mod test_group { 226 | use seq_macro::seq; 227 | 228 | // Source of truth. Call a given macro passing nproc as argument. 229 | macro_rules! pass_nproc { 230 | ($mac:ident) => { 231 | $mac! { 256 } 232 | }; 233 | } 234 | 235 | macro_rules! literal_identity_macro { 236 | ($nproc:literal) => { 237 | $nproc 238 | }; 239 | } 240 | 241 | const NPROC: usize = pass_nproc!(literal_identity_macro); 242 | 243 | pub struct Proc; 244 | 245 | impl Proc { 246 | const fn new() -> Self { 247 | Proc 248 | } 249 | } 250 | 251 | pub struct Mutex(T); 252 | 253 | impl Mutex { 254 | const fn new(_name: &'static str, value: T) -> Self { 255 | Mutex(value) 256 | } 257 | } 258 | 259 | macro_rules! make_procs_array { 260 | ($nproc:literal) => { 261 | seq!(N in 0..$nproc { [#(Proc::new(),)*] }) 262 | } 263 | } 264 | 265 | pub static PROCS: Mutex<[Proc; NPROC]> = Mutex::new("procs", pass_nproc!(make_procs_array)); 266 | } 267 | 268 | #[test] 269 | fn test_nested() { 270 | let mut vec = Vec::new(); 271 | macro_rules! some_macro { 272 | ($($t:ident,)*) => { 273 | vec.push(stringify!($($t)*)); 274 | }; 275 | } 276 | 277 | seq!(I in 1..=3 { 278 | #( 279 | seq!(J in 1..=I { 280 | some_macro!( 281 | #(T~J,)* 282 | ); 283 | }); 284 | )* 285 | }); 286 | 287 | assert_eq!(vec, ["T1", "T1 T2", "T1 T2 T3"]); 288 | } 289 | -------------------------------------------------------------------------------- /tests/ui/compile-error-span.rs: -------------------------------------------------------------------------------- 1 | use seq_macro::seq; 2 | 3 | seq!(N in 0..4 { 4 | compile_error!(concat!("error number ", stringify!(N))); 5 | }); 6 | 7 | fn main() {} 8 | -------------------------------------------------------------------------------- /tests/ui/compile-error-span.stderr: -------------------------------------------------------------------------------- 1 | error: error number 0 2 | --> tests/ui/compile-error-span.rs:4:5 3 | | 4 | 4 | compile_error!(concat!("error number ", stringify!(N))); 5 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | 7 | error: error number 1 8 | --> tests/ui/compile-error-span.rs:4:5 9 | | 10 | 4 | compile_error!(concat!("error number ", stringify!(N))); 11 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 12 | 13 | error: error number 2 14 | --> tests/ui/compile-error-span.rs:4:5 15 | | 16 | 4 | compile_error!(concat!("error number ", stringify!(N))); 17 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 18 | 19 | error: error number 3 20 | --> tests/ui/compile-error-span.rs:4:5 21 | | 22 | 4 | compile_error!(concat!("error number ", stringify!(N))); 23 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 24 | -------------------------------------------------------------------------------- /tests/ui/ident-span.rs: -------------------------------------------------------------------------------- 1 | use seq_macro::seq; 2 | 3 | seq!(N in 0..1 { 4 | fn main() { 5 | let _ = Missing~N; 6 | } 7 | }); 8 | -------------------------------------------------------------------------------- /tests/ui/ident-span.stderr: -------------------------------------------------------------------------------- 1 | error[E0425]: cannot find value `Missing0` in this scope 2 | --> tests/ui/ident-span.rs:5:17 3 | | 4 | 5 | let _ = Missing~N; 5 | | ^^^^^^^ not found in this scope 6 | -------------------------------------------------------------------------------- /tests/ui/kind-mismatch.rs: -------------------------------------------------------------------------------- 1 | use seq_macro::seq; 2 | 3 | seq!(N in 'a'..b'z' {}); 4 | 5 | fn main() {} 6 | -------------------------------------------------------------------------------- /tests/ui/kind-mismatch.stderr: -------------------------------------------------------------------------------- 1 | error: expected character literal 2 | --> tests/ui/kind-mismatch.rs:3:16 3 | | 4 | 3 | seq!(N in 'a'..b'z' {}); 5 | | ^^^^ 6 | -------------------------------------------------------------------------------- /tests/ui/suffix-mismatch.rs: -------------------------------------------------------------------------------- 1 | use seq_macro::seq; 2 | 3 | seq!(N in 0u8..1u16 {}); 4 | 5 | fn main() {} 6 | -------------------------------------------------------------------------------- /tests/ui/suffix-mismatch.stderr: -------------------------------------------------------------------------------- 1 | error: expected suffix `u8` 2 | --> tests/ui/suffix-mismatch.rs:3:16 3 | | 4 | 3 | seq!(N in 0u8..1u16 {}); 5 | | ^^^^ 6 | --------------------------------------------------------------------------------