├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches ├── Cargo.toml ├── README.md ├── lib.rs ├── main.rs └── timer.rs ├── rust-toolchain.toml ├── src ├── ext.rs ├── format.rs ├── ident_fragment.rs ├── lib.rs ├── runtime.rs ├── spanned.rs └── to_tokens.rs └── tests ├── compiletest.rs ├── test.rs └── ui ├── does-not-have-iter-interpolated-dup.rs ├── does-not-have-iter-interpolated-dup.stderr ├── does-not-have-iter-interpolated.rs ├── does-not-have-iter-interpolated.stderr ├── does-not-have-iter-separated.rs ├── does-not-have-iter-separated.stderr ├── does-not-have-iter.rs ├── does-not-have-iter.stderr ├── not-quotable.rs ├── not-quotable.stderr ├── not-repeatable.rs ├── not-repeatable.stderr ├── wrong-type-span.rs └── wrong-type-span.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, stable, beta, 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 | components: rust-src 35 | - name: Enable type layout randomization 36 | run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV 37 | if: matrix.rust == 'nightly' 38 | - run: cargo test 39 | - run: cargo run --manifest-path benches/Cargo.toml 40 | - uses: actions/upload-artifact@v4 41 | if: matrix.rust == 'nightly' && always() 42 | with: 43 | name: Cargo.lock 44 | path: Cargo.lock 45 | continue-on-error: true 46 | 47 | minimal: 48 | name: Minimal versions 49 | needs: pre_ci 50 | if: needs.pre_ci.outputs.continue 51 | runs-on: ubuntu-latest 52 | timeout-minutes: 45 53 | steps: 54 | - uses: actions/checkout@v4 55 | - uses: dtolnay/rust-toolchain@nightly 56 | - run: cargo generate-lockfile -Z minimal-versions 57 | - run: cargo check --locked 58 | 59 | doc: 60 | name: Documentation 61 | needs: pre_ci 62 | if: needs.pre_ci.outputs.continue 63 | runs-on: ubuntu-latest 64 | timeout-minutes: 45 65 | env: 66 | RUSTDOCFLAGS: -Dwarnings 67 | steps: 68 | - uses: actions/checkout@v4 69 | - uses: dtolnay/rust-toolchain@nightly 70 | with: 71 | components: rust-src 72 | - uses: dtolnay/install@cargo-docs-rs 73 | - run: cargo docs-rs 74 | 75 | clippy: 76 | name: Clippy 77 | runs-on: ubuntu-latest 78 | if: github.event_name != 'pull_request' 79 | timeout-minutes: 45 80 | steps: 81 | - uses: actions/checkout@v4 82 | - uses: dtolnay/rust-toolchain@nightly 83 | with: 84 | components: clippy, rust-src 85 | - run: cargo clippy --tests --workspace -- -Dclippy::all -Dclippy::pedantic 86 | 87 | miri: 88 | name: Miri 89 | needs: pre_ci 90 | if: needs.pre_ci.outputs.continue 91 | runs-on: ubuntu-latest 92 | timeout-minutes: 45 93 | steps: 94 | - uses: actions/checkout@v4 95 | - uses: dtolnay/rust-toolchain@miri 96 | with: 97 | toolchain: nightly-2025-05-16 # https://github.com/rust-lang/miri/issues/4323 98 | - run: cargo miri setup 99 | - run: cargo miri test 100 | env: 101 | MIRIFLAGS: -Zmiri-strict-provenance 102 | 103 | outdated: 104 | name: Outdated 105 | runs-on: ubuntu-latest 106 | if: github.event_name != 'pull_request' 107 | timeout-minutes: 45 108 | steps: 109 | - uses: actions/checkout@v4 110 | - uses: dtolnay/rust-toolchain@stable 111 | - uses: dtolnay/install@cargo-outdated 112 | - run: cargo outdated --workspace --exit-code 1 113 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "quote" 3 | version = "1.0.40" 4 | authors = ["David Tolnay "] 5 | autobenches = false 6 | categories = ["development-tools::procedural-macro-helpers"] 7 | description = "Quasi-quoting macro quote!(...)" 8 | documentation = "https://docs.rs/quote/" 9 | edition = "2018" 10 | keywords = ["macros", "syn"] 11 | license = "MIT OR Apache-2.0" 12 | repository = "https://github.com/dtolnay/quote" 13 | rust-version = "1.56" 14 | 15 | [dependencies] 16 | proc-macro2 = { version = "1.0.80", default-features = false } 17 | 18 | [dev-dependencies] 19 | rustversion = "1.0" 20 | trybuild = { version = "1.0.66", features = ["diff"] } 21 | 22 | [features] 23 | default = ["proc-macro"] 24 | # Disabling the proc-macro feature removes the dynamic library dependency on 25 | # libproc_macro in the rustc compiler. 26 | proc-macro = ["proc-macro2/proc-macro"] 27 | 28 | [workspace] 29 | members = ["benches"] 30 | 31 | [package.metadata.docs.rs] 32 | targets = ["x86_64-unknown-linux-gnu"] 33 | rustdoc-args = [ 34 | "--generate-link-to-definition", 35 | "--extern-html-root-url=core=https://doc.rust-lang.org", 36 | "--extern-html-root-url=alloc=https://doc.rust-lang.org", 37 | "--extern-html-root-url=std=https://doc.rust-lang.org", 38 | ] 39 | -------------------------------------------------------------------------------- /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 | Rust Quasi-Quoting 2 | ================== 3 | 4 | [github](https://github.com/dtolnay/quote) 5 | [crates.io](https://crates.io/crates/quote) 6 | [docs.rs](https://docs.rs/quote) 7 | [build status](https://github.com/dtolnay/quote/actions?query=branch%3Amaster) 8 | 9 | This crate provides the [`quote!`] macro for turning Rust syntax tree data 10 | structures into tokens of source code. 11 | 12 | [`quote!`]: https://docs.rs/quote/1.0/quote/macro.quote.html 13 | 14 | Procedural macros in Rust receive a stream of tokens as input, execute arbitrary 15 | Rust code to determine how to manipulate those tokens, and produce a stream of 16 | tokens to hand back to the compiler to compile into the caller's crate. 17 | Quasi-quoting is a solution to one piece of that — producing tokens to 18 | return to the compiler. 19 | 20 | The idea of quasi-quoting is that we write *code* that we treat as *data*. 21 | Within the `quote!` macro, we can write what looks like code to our text editor 22 | or IDE. We get all the benefits of the editor's brace matching, syntax 23 | highlighting, indentation, and maybe autocompletion. But rather than compiling 24 | that as code into the current crate, we can treat it as data, pass it around, 25 | mutate it, and eventually hand it back to the compiler as tokens to compile into 26 | the macro caller's crate. 27 | 28 | This crate is motivated by the procedural macro use case, but is a 29 | general-purpose Rust quasi-quoting library and is not specific to procedural 30 | macros. 31 | 32 | ```toml 33 | [dependencies] 34 | quote = "1.0" 35 | ``` 36 | 37 | *Version requirement: Quote supports rustc 1.56 and up.*
38 | [*Release notes*](https://github.com/dtolnay/quote/releases) 39 | 40 |
41 | 42 | ## Syntax 43 | 44 | The quote crate provides a [`quote!`] macro within which you can write Rust code 45 | that gets packaged into a [`TokenStream`] and can be treated as data. You should 46 | think of `TokenStream` as representing a fragment of Rust source code. 47 | 48 | [`TokenStream`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.TokenStream.html 49 | 50 | Within the `quote!` macro, interpolation is done with `#var`. Any type 51 | implementing the [`quote::ToTokens`] trait can be interpolated. This includes 52 | most Rust primitive types as well as most of the syntax tree types from [`syn`]. 53 | 54 | [`quote::ToTokens`]: https://docs.rs/quote/1.0/quote/trait.ToTokens.html 55 | [`syn`]: https://github.com/dtolnay/syn 56 | 57 | ```rust 58 | let tokens = quote! { 59 | struct SerializeWith #generics #where_clause { 60 | value: &'a #field_ty, 61 | phantom: core::marker::PhantomData<#item_ty>, 62 | } 63 | 64 | impl #generics serde::Serialize for SerializeWith #generics #where_clause { 65 | fn serialize(&self, serializer: S) -> Result 66 | where 67 | S: serde::Serializer, 68 | { 69 | #path(self.value, serializer) 70 | } 71 | } 72 | 73 | SerializeWith { 74 | value: #value, 75 | phantom: core::marker::PhantomData::<#item_ty>, 76 | } 77 | }; 78 | ``` 79 | 80 |
81 | 82 | ## Repetition 83 | 84 | Repetition is done using `#(...)*` or `#(...),*` similar to `macro_rules!`. This 85 | iterates through the elements of any variable interpolated within the repetition 86 | and inserts a copy of the repetition body for each one. The variables in an 87 | interpolation may be a `Vec`, slice, `BTreeSet`, or any `Iterator`. 88 | 89 | - `#(#var)*` — no separators 90 | - `#(#var),*` — the character before the asterisk is used as a separator 91 | - `#( struct #var; )*` — the repetition can contain other things 92 | - `#( #k => println!("{}", #v), )*` — even multiple interpolations 93 | 94 | Note that there is a difference between `#(#var ,)*` and `#(#var),*`—the latter 95 | does not produce a trailing comma. This matches the behavior of delimiters in 96 | `macro_rules!`. 97 | 98 |
99 | 100 | ## Returning tokens to the compiler 101 | 102 | The `quote!` macro evaluates to an expression of type 103 | `proc_macro2::TokenStream`. Meanwhile Rust procedural macros are expected to 104 | return the type `proc_macro::TokenStream`. 105 | 106 | The difference between the two types is that `proc_macro` types are entirely 107 | specific to procedural macros and cannot ever exist in code outside of a 108 | procedural macro, while `proc_macro2` types may exist anywhere including tests 109 | and non-macro code like main.rs and build.rs. This is why even the procedural 110 | macro ecosystem is largely built around `proc_macro2`, because that ensures the 111 | libraries are unit testable and accessible in non-macro contexts. 112 | 113 | There is a [`From`]-conversion in both directions so returning the output of 114 | `quote!` from a procedural macro usually looks like `tokens.into()` or 115 | `proc_macro::TokenStream::from(tokens)`. 116 | 117 | [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html 118 | 119 |
120 | 121 | ## Examples 122 | 123 | ### Combining quoted fragments 124 | 125 | Usually you don't end up constructing an entire final `TokenStream` in one 126 | piece. Different parts may come from different helper functions. The tokens 127 | produced by `quote!` themselves implement `ToTokens` and so can be interpolated 128 | into later `quote!` invocations to build up a final result. 129 | 130 | ```rust 131 | let type_definition = quote! {...}; 132 | let methods = quote! {...}; 133 | 134 | let tokens = quote! { 135 | #type_definition 136 | #methods 137 | }; 138 | ``` 139 | 140 | ### Constructing identifiers 141 | 142 | Suppose we have an identifier `ident` which came from somewhere in a macro 143 | input and we need to modify it in some way for the macro output. Let's consider 144 | prepending the identifier with an underscore. 145 | 146 | Simply interpolating the identifier next to an underscore will not have the 147 | behavior of concatenating them. The underscore and the identifier will continue 148 | to be two separate tokens as if you had written `_ x`. 149 | 150 | ```rust 151 | // incorrect 152 | quote! { 153 | let mut _#ident = 0; 154 | } 155 | ``` 156 | 157 | The solution is to build a new identifier token with the correct value. As this 158 | is such a common case, the `format_ident!` macro provides a convenient utility 159 | for doing so correctly. 160 | 161 | ```rust 162 | let varname = format_ident!("_{}", ident); 163 | quote! { 164 | let mut #varname = 0; 165 | } 166 | ``` 167 | 168 | Alternatively, the APIs provided by Syn and proc-macro2 can be used to directly 169 | build the identifier. This is roughly equivalent to the above, but will not 170 | handle `ident` being a raw identifier. 171 | 172 | ```rust 173 | let concatenated = format!("_{}", ident); 174 | let varname = syn::Ident::new(&concatenated, ident.span()); 175 | quote! { 176 | let mut #varname = 0; 177 | } 178 | ``` 179 | 180 | ### Making method calls 181 | 182 | Let's say our macro requires some type specified in the macro input to have a 183 | constructor called `new`. We have the type in a variable called `field_type` of 184 | type `syn::Type` and want to invoke the constructor. 185 | 186 | ```rust 187 | // incorrect 188 | quote! { 189 | let value = #field_type::new(); 190 | } 191 | ``` 192 | 193 | This works only sometimes. If `field_type` is `String`, the expanded code 194 | contains `String::new()` which is fine. But if `field_type` is something like 195 | `Vec` then the expanded code is `Vec::new()` which is invalid syntax. 196 | Ordinarily in handwritten Rust we would write `Vec::::new()` but for macros 197 | often the following is more convenient. 198 | 199 | ```rust 200 | quote! { 201 | let value = <#field_type>::new(); 202 | } 203 | ``` 204 | 205 | This expands to `>::new()` which behaves correctly. 206 | 207 | A similar pattern is appropriate for trait methods. 208 | 209 | ```rust 210 | quote! { 211 | let value = <#field_type as core::default::Default>::default(); 212 | } 213 | ``` 214 | 215 |
216 | 217 | ## Hygiene 218 | 219 | Any interpolated tokens preserve the `Span` information provided by their 220 | `ToTokens` implementation. Tokens that originate within a `quote!` invocation 221 | are spanned with [`Span::call_site()`]. 222 | 223 | [`Span::call_site()`]: https://docs.rs/proc-macro2/1.0/proc_macro2/struct.Span.html#method.call_site 224 | 225 | A different span can be provided explicitly through the [`quote_spanned!`] 226 | macro. 227 | 228 | [`quote_spanned!`]: https://docs.rs/quote/1.0/quote/macro.quote_spanned.html 229 | 230 |
231 | 232 | ## Non-macro code generators 233 | 234 | When using `quote` in a build.rs or main.rs and writing the output out to a 235 | file, consider having the code generator pass the tokens through [prettyplease] 236 | before writing. This way if an error occurs in the generated code it is 237 | convenient for a human to read and debug. 238 | 239 | Be aware that no kind of hygiene or span information is retained when tokens are 240 | written to a file; the conversion from tokens to source code is lossy. 241 | 242 | Example usage in build.rs: 243 | 244 | ```rust 245 | let output = quote! { ... }; 246 | let syntax_tree = syn::parse2(output).unwrap(); 247 | let formatted = prettyplease::unparse(&syntax_tree); 248 | 249 | let out_dir = env::var_os("OUT_DIR").unwrap(); 250 | let dest_path = Path::new(&out_dir).join("out.rs"); 251 | fs::write(dest_path, formatted).unwrap(); 252 | ``` 253 | 254 | [prettyplease]: https://github.com/dtolnay/prettyplease 255 | 256 |
257 | 258 | #### License 259 | 260 | 261 | Licensed under either of Apache License, Version 262 | 2.0 or MIT license at your option. 263 | 264 | 265 |
266 | 267 | 268 | Unless you explicitly state otherwise, any contribution intentionally submitted 269 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 270 | be dual licensed as above, without any additional terms or conditions. 271 | 272 | -------------------------------------------------------------------------------- /benches/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "quote-benchmark" 3 | version = "0.0.0" 4 | authors = ["David Tolnay "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | publish = false 8 | 9 | [lib] 10 | proc-macro = true 11 | path = "lib.rs" 12 | 13 | [[bin]] 14 | name = "quote-benchmark" 15 | path = "main.rs" 16 | 17 | [dependencies] 18 | proc-macro2 = "1.0" 19 | quote = { path = ".." } 20 | termcolor = "1.1" 21 | -------------------------------------------------------------------------------- /benches/README.md: -------------------------------------------------------------------------------- 1 | Example output: 2 | 3 |
 4 | $ cargo run && cargo run --release
 5 | 
 6 |    Compiling quote v1.0.35
 7 |    Compiling quote-benchmark v0.0.0
 8 | macro in debug mode: 440 micros
 9 |     Finished dev [unoptimized + debuginfo] target(s) in 4.39s
10 |      Running `target/debug/quote-benchmark`
11 | non-macro in debug mode: 537 micros
12 |    Compiling quote v1.0.35
13 |    Compiling quote-benchmark v0.0.0
14 | macro in release mode: 423 micros
15 |     Finished release [optimized] target(s) in 4.00s
16 |      Running `target/release/quote-benchmark`
17 | non-macro in release mode: 134 micros
18 | 
19 | -------------------------------------------------------------------------------- /benches/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow( 2 | clippy::cast_lossless, 3 | clippy::let_underscore_untyped, 4 | clippy::uninlined_format_args 5 | )] 6 | 7 | use quote::quote; 8 | 9 | #[allow(unused_macros)] 10 | macro_rules! benchmark { 11 | (|$ident:ident| $quote:expr) => { 12 | mod timer; 13 | 14 | use proc_macro::TokenStream; 15 | use proc_macro2::Ident; 16 | 17 | #[proc_macro] 18 | pub fn run_quote_benchmark(input: TokenStream) -> TokenStream { 19 | let input = proc_macro2::TokenStream::from(input); 20 | let span = input.into_iter().next().unwrap().span(); 21 | let $ident = Ident::new("Response", span); 22 | timer::time("macro", || proc_macro::TokenStream::from($quote)); 23 | TokenStream::new() 24 | } 25 | }; 26 | } 27 | 28 | #[allow(unused_imports)] 29 | use benchmark; 30 | 31 | crate::benchmark! { 32 | |ident| quote! { 33 | impl<'de> _serde::Deserialize<'de> for #ident { 34 | fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result 35 | where 36 | __D: _serde::Deserializer<'de>, 37 | { 38 | #[allow(non_camel_case_types)] 39 | enum __Field { 40 | __field0, 41 | __field1, 42 | __ignore, 43 | } 44 | struct __FieldVisitor; 45 | impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { 46 | type Value = __Field; 47 | fn expecting( 48 | &self, 49 | __formatter: &mut _serde::export::Formatter, 50 | ) -> _serde::export::fmt::Result { 51 | _serde::export::Formatter::write_str(__formatter, "field identifier") 52 | } 53 | fn visit_u64<__E>(self, __value: u64) -> _serde::export::Result 54 | where 55 | __E: _serde::de::Error, 56 | { 57 | match __value { 58 | 0u64 => _serde::export::Ok(__Field::__field0), 59 | 1u64 => _serde::export::Ok(__Field::__field1), 60 | _ => _serde::export::Err(_serde::de::Error::invalid_value( 61 | _serde::de::Unexpected::Unsigned(__value), 62 | &"field index 0 <= i < 2", 63 | )), 64 | } 65 | } 66 | fn visit_str<__E>(self, __value: &str) -> _serde::export::Result 67 | where 68 | __E: _serde::de::Error, 69 | { 70 | match __value { 71 | "id" => _serde::export::Ok(__Field::__field0), 72 | "s" => _serde::export::Ok(__Field::__field1), 73 | _ => _serde::export::Ok(__Field::__ignore), 74 | } 75 | } 76 | fn visit_bytes<__E>( 77 | self, 78 | __value: &[u8], 79 | ) -> _serde::export::Result 80 | where 81 | __E: _serde::de::Error, 82 | { 83 | match __value { 84 | b"id" => _serde::export::Ok(__Field::__field0), 85 | b"s" => _serde::export::Ok(__Field::__field1), 86 | _ => _serde::export::Ok(__Field::__ignore), 87 | } 88 | } 89 | } 90 | impl<'de> _serde::Deserialize<'de> for __Field { 91 | #[inline] 92 | fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result 93 | where 94 | __D: _serde::Deserializer<'de>, 95 | { 96 | _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) 97 | } 98 | } 99 | struct __Visitor<'de> { 100 | marker: _serde::export::PhantomData<#ident>, 101 | lifetime: _serde::export::PhantomData<&'de ()>, 102 | } 103 | impl<'de> _serde::de::Visitor<'de> for __Visitor<'de> { 104 | type Value = #ident; 105 | fn expecting( 106 | &self, 107 | __formatter: &mut _serde::export::Formatter, 108 | ) -> _serde::export::fmt::Result { 109 | _serde::export::Formatter::write_str(__formatter, "struct") 110 | } 111 | #[inline] 112 | fn visit_seq<__A>( 113 | self, 114 | mut __seq: __A, 115 | ) -> _serde::export::Result 116 | where 117 | __A: _serde::de::SeqAccess<'de>, 118 | { 119 | let __field0 = 120 | match try!(_serde::de::SeqAccess::next_element::(&mut __seq)) { 121 | _serde::export::Some(__value) => __value, 122 | _serde::export::None => { 123 | return _serde::export::Err(_serde::de::Error::invalid_length( 124 | 0usize, 125 | &"struct with 2 elements", 126 | )); 127 | } 128 | }; 129 | let __field1 = 130 | match try!(_serde::de::SeqAccess::next_element::(&mut __seq)) { 131 | _serde::export::Some(__value) => __value, 132 | _serde::export::None => { 133 | return _serde::export::Err(_serde::de::Error::invalid_length( 134 | 1usize, 135 | &"struct with 2 elements", 136 | )); 137 | } 138 | }; 139 | _serde::export::Ok(#ident { 140 | id: __field0, 141 | s: __field1, 142 | }) 143 | } 144 | #[inline] 145 | fn visit_map<__A>( 146 | self, 147 | mut __map: __A, 148 | ) -> _serde::export::Result 149 | where 150 | __A: _serde::de::MapAccess<'de>, 151 | { 152 | let mut __field0: _serde::export::Option = _serde::export::None; 153 | let mut __field1: _serde::export::Option = _serde::export::None; 154 | while let _serde::export::Some(__key) = 155 | try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) 156 | { 157 | match __key { 158 | __Field::__field0 => { 159 | if _serde::export::Option::is_some(&__field0) { 160 | return _serde::export::Err( 161 | <__A::Error as _serde::de::Error>::duplicate_field("id"), 162 | ); 163 | } 164 | __field0 = _serde::export::Some( 165 | try!(_serde::de::MapAccess::next_value::(&mut __map)), 166 | ); 167 | } 168 | __Field::__field1 => { 169 | if _serde::export::Option::is_some(&__field1) { 170 | return _serde::export::Err( 171 | <__A::Error as _serde::de::Error>::duplicate_field("s"), 172 | ); 173 | } 174 | __field1 = _serde::export::Some( 175 | try!(_serde::de::MapAccess::next_value::(&mut __map)), 176 | ); 177 | } 178 | _ => { 179 | let _ = try!(_serde::de::MapAccess::next_value::< 180 | _serde::de::IgnoredAny, 181 | >(&mut __map)); 182 | } 183 | } 184 | } 185 | let __field0 = match __field0 { 186 | _serde::export::Some(__field0) => __field0, 187 | _serde::export::None => try!(_serde::private::de::missing_field("id")), 188 | }; 189 | let __field1 = match __field1 { 190 | _serde::export::Some(__field1) => __field1, 191 | _serde::export::None => try!(_serde::private::de::missing_field("s")), 192 | }; 193 | _serde::export::Ok(#ident { 194 | id: __field0, 195 | s: __field1, 196 | }) 197 | } 198 | } 199 | const FIELDS: &'static [&'static str] = &["id", "s"]; 200 | _serde::Deserializer::deserialize_struct( 201 | __deserializer, 202 | stringify!(#ident), 203 | FIELDS, 204 | __Visitor { 205 | marker: _serde::export::PhantomData::<#ident>, 206 | lifetime: _serde::export::PhantomData, 207 | }, 208 | ) 209 | } 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /benches/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unknown_lints, special_module_name)] 2 | #![allow( 3 | clippy::cast_lossless, 4 | clippy::let_underscore_untyped, 5 | clippy::uninlined_format_args 6 | )] 7 | 8 | quote_benchmark::run_quote_benchmark!(_); 9 | 10 | mod benchmark { 11 | macro_rules! benchmark { 12 | (|$ident:ident| $quote:expr) => { 13 | use proc_macro2::{Ident, Span}; 14 | 15 | pub fn quote() -> proc_macro2::TokenStream { 16 | let $ident = Ident::new("Response", Span::call_site()); 17 | $quote 18 | } 19 | }; 20 | } 21 | 22 | pub(crate) use benchmark; 23 | } 24 | 25 | use benchmark::benchmark; 26 | 27 | mod lib; 28 | mod timer; 29 | 30 | fn main() { 31 | timer::time("non-macro", lib::quote); 32 | } 33 | -------------------------------------------------------------------------------- /benches/timer.rs: -------------------------------------------------------------------------------- 1 | use std::io::Write; 2 | use std::time::Instant; 3 | use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; 4 | 5 | const ITERATIONS: u32 = 1000; 6 | 7 | pub fn time(name: &'static str, function: impl Fn() -> T) { 8 | let begin = Instant::now(); 9 | for _ in 0..ITERATIONS { 10 | let _ = function(); 11 | } 12 | let micros = (begin.elapsed() / ITERATIONS).as_micros(); 13 | let mode = ["release", "debug"][cfg!(debug_assertions) as usize]; 14 | let mut writer = StandardStream::stderr(ColorChoice::Auto); 15 | let _ = writer.set_color(ColorSpec::new().set_fg(Some(Color::Magenta))); 16 | let _ = writeln!(&mut writer, "{} in {} mode: {} micros", name, mode, micros); 17 | } 18 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | components = ["rust-src"] 3 | -------------------------------------------------------------------------------- /src/ext.rs: -------------------------------------------------------------------------------- 1 | use super::ToTokens; 2 | use core::iter; 3 | use proc_macro2::{TokenStream, TokenTree}; 4 | 5 | /// TokenStream extension trait with methods for appending tokens. 6 | /// 7 | /// This trait is sealed and cannot be implemented outside of the `quote` crate. 8 | pub trait TokenStreamExt: private::Sealed { 9 | /// For use by `ToTokens` implementations. 10 | /// 11 | /// Appends the token specified to this list of tokens. 12 | fn append(&mut self, token: U) 13 | where 14 | U: Into; 15 | 16 | /// For use by `ToTokens` implementations. 17 | /// 18 | /// ``` 19 | /// # use quote::{quote, TokenStreamExt, ToTokens}; 20 | /// # use proc_macro2::TokenStream; 21 | /// # 22 | /// struct X; 23 | /// 24 | /// impl ToTokens for X { 25 | /// fn to_tokens(&self, tokens: &mut TokenStream) { 26 | /// tokens.append_all(&[true, false]); 27 | /// } 28 | /// } 29 | /// 30 | /// let tokens = quote!(#X); 31 | /// assert_eq!(tokens.to_string(), "true false"); 32 | /// ``` 33 | fn append_all(&mut self, iter: I) 34 | where 35 | I: IntoIterator, 36 | I::Item: ToTokens; 37 | 38 | /// For use by `ToTokens` implementations. 39 | /// 40 | /// Appends all of the items in the iterator `I`, separated by the tokens 41 | /// `U`. 42 | fn append_separated(&mut self, iter: I, op: U) 43 | where 44 | I: IntoIterator, 45 | I::Item: ToTokens, 46 | U: ToTokens; 47 | 48 | /// For use by `ToTokens` implementations. 49 | /// 50 | /// Appends all tokens in the iterator `I`, appending `U` after each 51 | /// element, including after the last element of the iterator. 52 | fn append_terminated(&mut self, iter: I, term: U) 53 | where 54 | I: IntoIterator, 55 | I::Item: ToTokens, 56 | U: ToTokens; 57 | } 58 | 59 | impl TokenStreamExt for TokenStream { 60 | fn append(&mut self, token: U) 61 | where 62 | U: Into, 63 | { 64 | self.extend(iter::once(token.into())); 65 | } 66 | 67 | fn append_all(&mut self, iter: I) 68 | where 69 | I: IntoIterator, 70 | I::Item: ToTokens, 71 | { 72 | for token in iter { 73 | token.to_tokens(self); 74 | } 75 | } 76 | 77 | fn append_separated(&mut self, iter: I, op: U) 78 | where 79 | I: IntoIterator, 80 | I::Item: ToTokens, 81 | U: ToTokens, 82 | { 83 | for (i, token) in iter.into_iter().enumerate() { 84 | if i > 0 { 85 | op.to_tokens(self); 86 | } 87 | token.to_tokens(self); 88 | } 89 | } 90 | 91 | fn append_terminated(&mut self, iter: I, term: U) 92 | where 93 | I: IntoIterator, 94 | I::Item: ToTokens, 95 | U: ToTokens, 96 | { 97 | for token in iter { 98 | token.to_tokens(self); 99 | term.to_tokens(self); 100 | } 101 | } 102 | } 103 | 104 | mod private { 105 | use proc_macro2::TokenStream; 106 | 107 | pub trait Sealed {} 108 | 109 | impl Sealed for TokenStream {} 110 | } 111 | -------------------------------------------------------------------------------- /src/format.rs: -------------------------------------------------------------------------------- 1 | /// Formatting macro for constructing `Ident`s. 2 | /// 3 | ///
4 | /// 5 | /// # Syntax 6 | /// 7 | /// Syntax is copied from the [`format!`] macro, supporting both positional and 8 | /// named arguments. 9 | /// 10 | /// Only a limited set of formatting traits are supported. The current mapping 11 | /// of format types to traits is: 12 | /// 13 | /// * `{}` ⇒ [`IdentFragment`] 14 | /// * `{:o}` ⇒ [`Octal`](std::fmt::Octal) 15 | /// * `{:x}` ⇒ [`LowerHex`](std::fmt::LowerHex) 16 | /// * `{:X}` ⇒ [`UpperHex`](std::fmt::UpperHex) 17 | /// * `{:b}` ⇒ [`Binary`](std::fmt::Binary) 18 | /// 19 | /// See [`std::fmt`] for more information. 20 | /// 21 | ///
22 | /// 23 | /// # IdentFragment 24 | /// 25 | /// Unlike `format!`, this macro uses the [`IdentFragment`] formatting trait by 26 | /// default. This trait is like `Display`, with a few differences: 27 | /// 28 | /// * `IdentFragment` is only implemented for a limited set of types, such as 29 | /// unsigned integers and strings. 30 | /// * [`Ident`] arguments will have their `r#` prefixes stripped, if present. 31 | /// 32 | /// [`IdentFragment`]: crate::IdentFragment 33 | /// [`Ident`]: proc_macro2::Ident 34 | /// 35 | ///
36 | /// 37 | /// # Hygiene 38 | /// 39 | /// The [`Span`] of the first `Ident` argument is used as the span of the final 40 | /// identifier, falling back to [`Span::call_site`] when no identifiers are 41 | /// provided. 42 | /// 43 | /// ``` 44 | /// # use quote::format_ident; 45 | /// # let ident = format_ident!("Ident"); 46 | /// // If `ident` is an Ident, the span of `my_ident` will be inherited from it. 47 | /// let my_ident = format_ident!("My{}{}", ident, "IsCool"); 48 | /// assert_eq!(my_ident, "MyIdentIsCool"); 49 | /// ``` 50 | /// 51 | /// Alternatively, the span can be overridden by passing the `span` named 52 | /// argument. 53 | /// 54 | /// ``` 55 | /// # use quote::format_ident; 56 | /// # const IGNORE_TOKENS: &'static str = stringify! { 57 | /// let my_span = /* ... */; 58 | /// # }; 59 | /// # let my_span = proc_macro2::Span::call_site(); 60 | /// format_ident!("MyIdent", span = my_span); 61 | /// ``` 62 | /// 63 | /// [`Span`]: proc_macro2::Span 64 | /// [`Span::call_site`]: proc_macro2::Span::call_site 65 | /// 66 | ///


67 | /// 68 | /// # Panics 69 | /// 70 | /// This method will panic if the resulting formatted string is not a valid 71 | /// identifier. 72 | /// 73 | ///
74 | /// 75 | /// # Examples 76 | /// 77 | /// Composing raw and non-raw identifiers: 78 | /// ``` 79 | /// # use quote::format_ident; 80 | /// let my_ident = format_ident!("My{}", "Ident"); 81 | /// assert_eq!(my_ident, "MyIdent"); 82 | /// 83 | /// let raw = format_ident!("r#Raw"); 84 | /// assert_eq!(raw, "r#Raw"); 85 | /// 86 | /// let my_ident_raw = format_ident!("{}Is{}", my_ident, raw); 87 | /// assert_eq!(my_ident_raw, "MyIdentIsRaw"); 88 | /// ``` 89 | /// 90 | /// Integer formatting options: 91 | /// ``` 92 | /// # use quote::format_ident; 93 | /// let num: u32 = 10; 94 | /// 95 | /// let decimal = format_ident!("Id_{}", num); 96 | /// assert_eq!(decimal, "Id_10"); 97 | /// 98 | /// let octal = format_ident!("Id_{:o}", num); 99 | /// assert_eq!(octal, "Id_12"); 100 | /// 101 | /// let binary = format_ident!("Id_{:b}", num); 102 | /// assert_eq!(binary, "Id_1010"); 103 | /// 104 | /// let lower_hex = format_ident!("Id_{:x}", num); 105 | /// assert_eq!(lower_hex, "Id_a"); 106 | /// 107 | /// let upper_hex = format_ident!("Id_{:X}", num); 108 | /// assert_eq!(upper_hex, "Id_A"); 109 | /// ``` 110 | #[macro_export] 111 | macro_rules! format_ident { 112 | ($fmt:expr) => { 113 | $crate::format_ident_impl!([ 114 | $crate::__private::Option::None, 115 | $fmt 116 | ]) 117 | }; 118 | 119 | ($fmt:expr, $($rest:tt)*) => { 120 | $crate::format_ident_impl!([ 121 | $crate::__private::Option::None, 122 | $fmt 123 | ] $($rest)*) 124 | }; 125 | } 126 | 127 | #[macro_export] 128 | #[doc(hidden)] 129 | macro_rules! format_ident_impl { 130 | // Final state 131 | ([$span:expr, $($fmt:tt)*]) => { 132 | $crate::__private::mk_ident( 133 | &$crate::__private::format!($($fmt)*), 134 | $span, 135 | ) 136 | }; 137 | 138 | // Span argument 139 | ([$old:expr, $($fmt:tt)*] span = $span:expr) => { 140 | $crate::format_ident_impl!([$old, $($fmt)*] span = $span,) 141 | }; 142 | ([$old:expr, $($fmt:tt)*] span = $span:expr, $($rest:tt)*) => { 143 | $crate::format_ident_impl!([ 144 | $crate::__private::Option::Some::<$crate::__private::Span>($span), 145 | $($fmt)* 146 | ] $($rest)*) 147 | }; 148 | 149 | // Named argument 150 | ([$span:expr, $($fmt:tt)*] $name:ident = $arg:expr) => { 151 | $crate::format_ident_impl!([$span, $($fmt)*] $name = $arg,) 152 | }; 153 | ([$span:expr, $($fmt:tt)*] $name:ident = $arg:expr, $($rest:tt)*) => { 154 | match $crate::__private::IdentFragmentAdapter(&$arg) { 155 | arg => $crate::format_ident_impl!([$span.or(arg.span()), $($fmt)*, $name = arg] $($rest)*), 156 | } 157 | }; 158 | 159 | // Positional argument 160 | ([$span:expr, $($fmt:tt)*] $arg:expr) => { 161 | $crate::format_ident_impl!([$span, $($fmt)*] $arg,) 162 | }; 163 | ([$span:expr, $($fmt:tt)*] $arg:expr, $($rest:tt)*) => { 164 | match $crate::__private::IdentFragmentAdapter(&$arg) { 165 | arg => $crate::format_ident_impl!([$span.or(arg.span()), $($fmt)*, arg] $($rest)*), 166 | } 167 | }; 168 | } 169 | -------------------------------------------------------------------------------- /src/ident_fragment.rs: -------------------------------------------------------------------------------- 1 | use alloc::borrow::Cow; 2 | use core::fmt; 3 | use proc_macro2::{Ident, Span}; 4 | 5 | /// Specialized formatting trait used by `format_ident!`. 6 | /// 7 | /// [`Ident`] arguments formatted using this trait will have their `r#` prefix 8 | /// stripped, if present. 9 | /// 10 | /// See [`format_ident!`] for more information. 11 | /// 12 | /// [`format_ident!`]: crate::format_ident 13 | pub trait IdentFragment { 14 | /// Format this value as an identifier fragment. 15 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result; 16 | 17 | /// Span associated with this `IdentFragment`. 18 | /// 19 | /// If non-`None`, may be inherited by formatted identifiers. 20 | fn span(&self) -> Option { 21 | None 22 | } 23 | } 24 | 25 | impl IdentFragment for &T { 26 | fn span(&self) -> Option { 27 | ::span(*self) 28 | } 29 | 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | IdentFragment::fmt(*self, f) 32 | } 33 | } 34 | 35 | impl IdentFragment for &mut T { 36 | fn span(&self) -> Option { 37 | ::span(*self) 38 | } 39 | 40 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 41 | IdentFragment::fmt(*self, f) 42 | } 43 | } 44 | 45 | impl IdentFragment for Ident { 46 | fn span(&self) -> Option { 47 | Some(self.span()) 48 | } 49 | 50 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 51 | let id = self.to_string(); 52 | if let Some(id) = id.strip_prefix("r#") { 53 | fmt::Display::fmt(id, f) 54 | } else { 55 | fmt::Display::fmt(&id[..], f) 56 | } 57 | } 58 | } 59 | 60 | impl IdentFragment for Cow<'_, T> 61 | where 62 | T: IdentFragment + ToOwned + ?Sized, 63 | { 64 | fn span(&self) -> Option { 65 | T::span(self) 66 | } 67 | 68 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 69 | T::fmt(self, f) 70 | } 71 | } 72 | 73 | // Limited set of types which this is implemented for, as we want to avoid types 74 | // which will often include non-identifier characters in their `Display` impl. 75 | macro_rules! ident_fragment_display { 76 | ($($T:ty),*) => { 77 | $( 78 | impl IdentFragment for $T { 79 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 80 | fmt::Display::fmt(self, f) 81 | } 82 | } 83 | )* 84 | }; 85 | } 86 | 87 | ident_fragment_display!(bool, str, String, char); 88 | ident_fragment_display!(u8, u16, u32, u64, u128, usize); 89 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![github]](https://github.com/dtolnay/quote) [![crates-io]](https://crates.io/crates/quote) [![docs-rs]](https://docs.rs/quote) 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 | //! This crate provides the [`quote!`] macro for turning Rust syntax tree data 10 | //! structures into tokens of source code. 11 | //! 12 | //! Procedural macros in Rust receive a stream of tokens as input, execute 13 | //! arbitrary Rust code to determine how to manipulate those tokens, and produce 14 | //! a stream of tokens to hand back to the compiler to compile into the caller's 15 | //! crate. Quasi-quoting is a solution to one piece of that — producing 16 | //! tokens to return to the compiler. 17 | //! 18 | //! The idea of quasi-quoting is that we write *code* that we treat as *data*. 19 | //! Within the `quote!` macro, we can write what looks like code to our text 20 | //! editor or IDE. We get all the benefits of the editor's brace matching, 21 | //! syntax highlighting, indentation, and maybe autocompletion. But rather than 22 | //! compiling that as code into the current crate, we can treat it as data, pass 23 | //! it around, mutate it, and eventually hand it back to the compiler as tokens 24 | //! to compile into the macro caller's crate. 25 | //! 26 | //! This crate is motivated by the procedural macro use case, but is a 27 | //! general-purpose Rust quasi-quoting library and is not specific to procedural 28 | //! macros. 29 | //! 30 | //! ```toml 31 | //! [dependencies] 32 | //! quote = "1.0" 33 | //! ``` 34 | //! 35 | //!
36 | //! 37 | //! # Example 38 | //! 39 | //! The following quasi-quoted block of code is something you might find in [a] 40 | //! procedural macro having to do with data structure serialization. The `#var` 41 | //! syntax performs interpolation of runtime variables into the quoted tokens. 42 | //! Check out the documentation of the [`quote!`] macro for more detail about 43 | //! the syntax. See also the [`quote_spanned!`] macro which is important for 44 | //! implementing hygienic procedural macros. 45 | //! 46 | //! [a]: https://serde.rs/ 47 | //! 48 | //! ``` 49 | //! # use quote::quote; 50 | //! # 51 | //! # let generics = ""; 52 | //! # let where_clause = ""; 53 | //! # let field_ty = ""; 54 | //! # let item_ty = ""; 55 | //! # let path = ""; 56 | //! # let value = ""; 57 | //! # 58 | //! let tokens = quote! { 59 | //! struct SerializeWith #generics #where_clause { 60 | //! value: &'a #field_ty, 61 | //! phantom: core::marker::PhantomData<#item_ty>, 62 | //! } 63 | //! 64 | //! impl #generics serde::Serialize for SerializeWith #generics #where_clause { 65 | //! fn serialize(&self, serializer: S) -> Result 66 | //! where 67 | //! S: serde::Serializer, 68 | //! { 69 | //! #path(self.value, serializer) 70 | //! } 71 | //! } 72 | //! 73 | //! SerializeWith { 74 | //! value: #value, 75 | //! phantom: core::marker::PhantomData::<#item_ty>, 76 | //! } 77 | //! }; 78 | //! ``` 79 | //! 80 | //!
81 | //! 82 | //! # Non-macro code generators 83 | //! 84 | //! When using `quote` in a build.rs or main.rs and writing the output out to a 85 | //! file, consider having the code generator pass the tokens through 86 | //! [prettyplease] before writing. This way if an error occurs in the generated 87 | //! code it is convenient for a human to read and debug. 88 | //! 89 | //! [prettyplease]: https://github.com/dtolnay/prettyplease 90 | 91 | // Quote types in rustdoc of other crates get linked to here. 92 | #![doc(html_root_url = "https://docs.rs/quote/1.0.40")] 93 | #![allow( 94 | clippy::doc_markdown, 95 | clippy::elidable_lifetime_names, 96 | clippy::missing_errors_doc, 97 | clippy::missing_panics_doc, 98 | clippy::module_name_repetitions, 99 | clippy::needless_lifetimes, 100 | // false positive https://github.com/rust-lang/rust-clippy/issues/6983 101 | clippy::wrong_self_convention, 102 | )] 103 | 104 | extern crate alloc; 105 | 106 | #[cfg(feature = "proc-macro")] 107 | extern crate proc_macro; 108 | 109 | mod ext; 110 | mod format; 111 | mod ident_fragment; 112 | mod to_tokens; 113 | 114 | // Not public API. 115 | #[doc(hidden)] 116 | #[path = "runtime.rs"] 117 | pub mod __private; 118 | 119 | pub use crate::ext::TokenStreamExt; 120 | pub use crate::ident_fragment::IdentFragment; 121 | pub use crate::to_tokens::ToTokens; 122 | 123 | // Not public API. 124 | #[doc(hidden)] 125 | pub mod spanned; 126 | 127 | macro_rules! __quote { 128 | ($quote:item) => { 129 | /// The whole point. 130 | /// 131 | /// Performs variable interpolation against the input and produces it as 132 | /// [`proc_macro2::TokenStream`]. 133 | /// 134 | /// Note: for returning tokens to the compiler in a procedural macro, use 135 | /// `.into()` on the result to convert to [`proc_macro::TokenStream`]. 136 | /// 137 | ///
138 | /// 139 | /// # Interpolation 140 | /// 141 | /// Variable interpolation is done with `#var` (similar to `$var` in 142 | /// `macro_rules!` macros). This grabs the `var` variable that is currently in 143 | /// scope and inserts it in that location in the output tokens. Any type 144 | /// implementing the [`ToTokens`] trait can be interpolated. This includes most 145 | /// Rust primitive types as well as most of the syntax tree types from the [Syn] 146 | /// crate. 147 | /// 148 | /// [Syn]: https://github.com/dtolnay/syn 149 | /// 150 | /// Repetition is done using `#(...)*` or `#(...),*` again similar to 151 | /// `macro_rules!`. This iterates through the elements of any variable 152 | /// interpolated within the repetition and inserts a copy of the repetition body 153 | /// for each one. The variables in an interpolation may be a `Vec`, slice, 154 | /// `BTreeSet`, or any `Iterator`. 155 | /// 156 | /// - `#(#var)*` — no separators 157 | /// - `#(#var),*` — the character before the asterisk is used as a separator 158 | /// - `#( struct #var; )*` — the repetition can contain other tokens 159 | /// - `#( #k => println!("{}", #v), )*` — even multiple interpolations 160 | /// 161 | ///
162 | /// 163 | /// # Hygiene 164 | /// 165 | /// Any interpolated tokens preserve the `Span` information provided by their 166 | /// `ToTokens` implementation. Tokens that originate within the `quote!` 167 | /// invocation are spanned with [`Span::call_site()`]. 168 | /// 169 | /// [`Span::call_site()`]: proc_macro2::Span::call_site 170 | /// 171 | /// A different span can be provided through the [`quote_spanned!`] macro. 172 | /// 173 | ///
174 | /// 175 | /// # Return type 176 | /// 177 | /// The macro evaluates to an expression of type `proc_macro2::TokenStream`. 178 | /// Meanwhile Rust procedural macros are expected to return the type 179 | /// `proc_macro::TokenStream`. 180 | /// 181 | /// The difference between the two types is that `proc_macro` types are entirely 182 | /// specific to procedural macros and cannot ever exist in code outside of a 183 | /// procedural macro, while `proc_macro2` types may exist anywhere including 184 | /// tests and non-macro code like main.rs and build.rs. This is why even the 185 | /// procedural macro ecosystem is largely built around `proc_macro2`, because 186 | /// that ensures the libraries are unit testable and accessible in non-macro 187 | /// contexts. 188 | /// 189 | /// There is a [`From`]-conversion in both directions so returning the output of 190 | /// `quote!` from a procedural macro usually looks like `tokens.into()` or 191 | /// `proc_macro::TokenStream::from(tokens)`. 192 | /// 193 | ///
194 | /// 195 | /// # Examples 196 | /// 197 | /// ### Procedural macro 198 | /// 199 | /// The structure of a basic procedural macro is as follows. Refer to the [Syn] 200 | /// crate for further useful guidance on using `quote!` as part of a procedural 201 | /// macro. 202 | /// 203 | /// [Syn]: https://github.com/dtolnay/syn 204 | /// 205 | /// ``` 206 | /// # #[cfg(any())] 207 | /// extern crate proc_macro; 208 | /// # extern crate proc_macro2; 209 | /// 210 | /// # #[cfg(any())] 211 | /// use proc_macro::TokenStream; 212 | /// # use proc_macro2::TokenStream; 213 | /// use quote::quote; 214 | /// 215 | /// # const IGNORE_TOKENS: &'static str = stringify! { 216 | /// #[proc_macro_derive(HeapSize)] 217 | /// # }; 218 | /// pub fn derive_heap_size(input: TokenStream) -> TokenStream { 219 | /// // Parse the input and figure out what implementation to generate... 220 | /// # const IGNORE_TOKENS: &'static str = stringify! { 221 | /// let name = /* ... */; 222 | /// let expr = /* ... */; 223 | /// # }; 224 | /// # 225 | /// # let name = 0; 226 | /// # let expr = 0; 227 | /// 228 | /// let expanded = quote! { 229 | /// // The generated impl. 230 | /// impl heapsize::HeapSize for #name { 231 | /// fn heap_size_of_children(&self) -> usize { 232 | /// #expr 233 | /// } 234 | /// } 235 | /// }; 236 | /// 237 | /// // Hand the output tokens back to the compiler. 238 | /// TokenStream::from(expanded) 239 | /// } 240 | /// ``` 241 | /// 242 | ///


243 | /// 244 | /// ### Combining quoted fragments 245 | /// 246 | /// Usually you don't end up constructing an entire final `TokenStream` in one 247 | /// piece. Different parts may come from different helper functions. The tokens 248 | /// produced by `quote!` themselves implement `ToTokens` and so can be 249 | /// interpolated into later `quote!` invocations to build up a final result. 250 | /// 251 | /// ``` 252 | /// # use quote::quote; 253 | /// # 254 | /// let type_definition = quote! {...}; 255 | /// let methods = quote! {...}; 256 | /// 257 | /// let tokens = quote! { 258 | /// #type_definition 259 | /// #methods 260 | /// }; 261 | /// ``` 262 | /// 263 | ///


264 | /// 265 | /// ### Constructing identifiers 266 | /// 267 | /// Suppose we have an identifier `ident` which came from somewhere in a macro 268 | /// input and we need to modify it in some way for the macro output. Let's 269 | /// consider prepending the identifier with an underscore. 270 | /// 271 | /// Simply interpolating the identifier next to an underscore will not have the 272 | /// behavior of concatenating them. The underscore and the identifier will 273 | /// continue to be two separate tokens as if you had written `_ x`. 274 | /// 275 | /// ``` 276 | /// # use proc_macro2::{self as syn, Span}; 277 | /// # use quote::quote; 278 | /// # 279 | /// # let ident = syn::Ident::new("i", Span::call_site()); 280 | /// # 281 | /// // incorrect 282 | /// quote! { 283 | /// let mut _#ident = 0; 284 | /// } 285 | /// # ; 286 | /// ``` 287 | /// 288 | /// The solution is to build a new identifier token with the correct value. As 289 | /// this is such a common case, the [`format_ident!`] macro provides a 290 | /// convenient utility for doing so correctly. 291 | /// 292 | /// ``` 293 | /// # use proc_macro2::{Ident, Span}; 294 | /// # use quote::{format_ident, quote}; 295 | /// # 296 | /// # let ident = Ident::new("i", Span::call_site()); 297 | /// # 298 | /// let varname = format_ident!("_{}", ident); 299 | /// quote! { 300 | /// let mut #varname = 0; 301 | /// } 302 | /// # ; 303 | /// ``` 304 | /// 305 | /// Alternatively, the APIs provided by Syn and proc-macro2 can be used to 306 | /// directly build the identifier. This is roughly equivalent to the above, but 307 | /// will not handle `ident` being a raw identifier. 308 | /// 309 | /// ``` 310 | /// # use proc_macro2::{self as syn, Span}; 311 | /// # use quote::quote; 312 | /// # 313 | /// # let ident = syn::Ident::new("i", Span::call_site()); 314 | /// # 315 | /// let concatenated = format!("_{}", ident); 316 | /// let varname = syn::Ident::new(&concatenated, ident.span()); 317 | /// quote! { 318 | /// let mut #varname = 0; 319 | /// } 320 | /// # ; 321 | /// ``` 322 | /// 323 | ///


324 | /// 325 | /// ### Making method calls 326 | /// 327 | /// Let's say our macro requires some type specified in the macro input to have 328 | /// a constructor called `new`. We have the type in a variable called 329 | /// `field_type` of type `syn::Type` and want to invoke the constructor. 330 | /// 331 | /// ``` 332 | /// # use quote::quote; 333 | /// # 334 | /// # let field_type = quote!(...); 335 | /// # 336 | /// // incorrect 337 | /// quote! { 338 | /// let value = #field_type::new(); 339 | /// } 340 | /// # ; 341 | /// ``` 342 | /// 343 | /// This works only sometimes. If `field_type` is `String`, the expanded code 344 | /// contains `String::new()` which is fine. But if `field_type` is something 345 | /// like `Vec` then the expanded code is `Vec::new()` which is invalid 346 | /// syntax. Ordinarily in handwritten Rust we would write `Vec::::new()` 347 | /// but for macros often the following is more convenient. 348 | /// 349 | /// ``` 350 | /// # use quote::quote; 351 | /// # 352 | /// # let field_type = quote!(...); 353 | /// # 354 | /// quote! { 355 | /// let value = <#field_type>::new(); 356 | /// } 357 | /// # ; 358 | /// ``` 359 | /// 360 | /// This expands to `>::new()` which behaves correctly. 361 | /// 362 | /// A similar pattern is appropriate for trait methods. 363 | /// 364 | /// ``` 365 | /// # use quote::quote; 366 | /// # 367 | /// # let field_type = quote!(...); 368 | /// # 369 | /// quote! { 370 | /// let value = <#field_type as core::default::Default>::default(); 371 | /// } 372 | /// # ; 373 | /// ``` 374 | /// 375 | ///


376 | /// 377 | /// ### Interpolating text inside of doc comments 378 | /// 379 | /// Neither doc comments nor string literals get interpolation behavior in 380 | /// quote: 381 | /// 382 | /// ```compile_fail 383 | /// quote! { 384 | /// /// try to interpolate: #ident 385 | /// /// 386 | /// /// ... 387 | /// } 388 | /// ``` 389 | /// 390 | /// ```compile_fail 391 | /// quote! { 392 | /// #[doc = "try to interpolate: #ident"] 393 | /// } 394 | /// ``` 395 | /// 396 | /// Instead the best way to build doc comments that involve variables is by 397 | /// formatting the doc string literal outside of quote. 398 | /// 399 | /// ```rust 400 | /// # use proc_macro2::{Ident, Span}; 401 | /// # use quote::quote; 402 | /// # 403 | /// # const IGNORE: &str = stringify! { 404 | /// let msg = format!(...); 405 | /// # }; 406 | /// # 407 | /// # let ident = Ident::new("var", Span::call_site()); 408 | /// # let msg = format!("try to interpolate: {}", ident); 409 | /// quote! { 410 | /// #[doc = #msg] 411 | /// /// 412 | /// /// ... 413 | /// } 414 | /// # ; 415 | /// ``` 416 | /// 417 | ///


418 | /// 419 | /// ### Indexing into a tuple struct 420 | /// 421 | /// When interpolating indices of a tuple or tuple struct, we need them not to 422 | /// appears suffixed as integer literals by interpolating them as [`syn::Index`] 423 | /// instead. 424 | /// 425 | /// [`syn::Index`]: https://docs.rs/syn/2.0/syn/struct.Index.html 426 | /// 427 | /// ```compile_fail 428 | /// let i = 0usize..self.fields.len(); 429 | /// 430 | /// // expands to 0 + self.0usize.heap_size() + self.1usize.heap_size() + ... 431 | /// // which is not valid syntax 432 | /// quote! { 433 | /// 0 #( + self.#i.heap_size() )* 434 | /// } 435 | /// ``` 436 | /// 437 | /// ``` 438 | /// # use proc_macro2::{Ident, TokenStream}; 439 | /// # use quote::quote; 440 | /// # 441 | /// # mod syn { 442 | /// # use proc_macro2::{Literal, TokenStream}; 443 | /// # use quote::{ToTokens, TokenStreamExt}; 444 | /// # 445 | /// # pub struct Index(usize); 446 | /// # 447 | /// # impl From for Index { 448 | /// # fn from(i: usize) -> Self { 449 | /// # Index(i) 450 | /// # } 451 | /// # } 452 | /// # 453 | /// # impl ToTokens for Index { 454 | /// # fn to_tokens(&self, tokens: &mut TokenStream) { 455 | /// # tokens.append(Literal::usize_unsuffixed(self.0)); 456 | /// # } 457 | /// # } 458 | /// # } 459 | /// # 460 | /// # struct Struct { 461 | /// # fields: Vec, 462 | /// # } 463 | /// # 464 | /// # impl Struct { 465 | /// # fn example(&self) -> TokenStream { 466 | /// let i = (0..self.fields.len()).map(syn::Index::from); 467 | /// 468 | /// // expands to 0 + self.0.heap_size() + self.1.heap_size() + ... 469 | /// quote! { 470 | /// 0 #( + self.#i.heap_size() )* 471 | /// } 472 | /// # } 473 | /// # } 474 | /// ``` 475 | $quote 476 | }; 477 | } 478 | 479 | #[cfg(doc)] 480 | __quote![ 481 | #[macro_export] 482 | macro_rules! quote { 483 | ($($tt:tt)*) => { 484 | ... 485 | }; 486 | } 487 | ]; 488 | 489 | #[cfg(not(doc))] 490 | __quote![ 491 | #[macro_export] 492 | macro_rules! quote { 493 | () => { 494 | $crate::__private::TokenStream::new() 495 | }; 496 | 497 | // Special case rule for a single tt, for performance. 498 | ($tt:tt) => {{ 499 | let mut _s = $crate::__private::TokenStream::new(); 500 | $crate::quote_token!{$tt _s} 501 | _s 502 | }}; 503 | 504 | // Special case rules for two tts, for performance. 505 | (# $var:ident) => {{ 506 | let mut _s = $crate::__private::TokenStream::new(); 507 | $crate::ToTokens::to_tokens(&$var, &mut _s); 508 | _s 509 | }}; 510 | ($tt1:tt $tt2:tt) => {{ 511 | let mut _s = $crate::__private::TokenStream::new(); 512 | $crate::quote_token!{$tt1 _s} 513 | $crate::quote_token!{$tt2 _s} 514 | _s 515 | }}; 516 | 517 | // Rule for any other number of tokens. 518 | ($($tt:tt)*) => {{ 519 | let mut _s = $crate::__private::TokenStream::new(); 520 | $crate::quote_each_token!{_s $($tt)*} 521 | _s 522 | }}; 523 | } 524 | ]; 525 | 526 | macro_rules! __quote_spanned { 527 | ($quote_spanned:item) => { 528 | /// Same as `quote!`, but applies a given span to all tokens originating within 529 | /// the macro invocation. 530 | /// 531 | ///
532 | /// 533 | /// # Syntax 534 | /// 535 | /// A span expression of type [`Span`], followed by `=>`, followed by the tokens 536 | /// to quote. The span expression should be brief — use a variable for 537 | /// anything more than a few characters. There should be no space before the 538 | /// `=>` token. 539 | /// 540 | /// [`Span`]: proc_macro2::Span 541 | /// 542 | /// ``` 543 | /// # use proc_macro2::Span; 544 | /// # use quote::quote_spanned; 545 | /// # 546 | /// # const IGNORE_TOKENS: &'static str = stringify! { 547 | /// let span = /* ... */; 548 | /// # }; 549 | /// # let span = Span::call_site(); 550 | /// # let init = 0; 551 | /// 552 | /// // On one line, use parentheses. 553 | /// let tokens = quote_spanned!(span=> Box::into_raw(Box::new(#init))); 554 | /// 555 | /// // On multiple lines, place the span at the top and use braces. 556 | /// let tokens = quote_spanned! {span=> 557 | /// Box::into_raw(Box::new(#init)) 558 | /// }; 559 | /// ``` 560 | /// 561 | /// The lack of space before the `=>` should look jarring to Rust programmers 562 | /// and this is intentional. The formatting is designed to be visibly 563 | /// off-balance and draw the eye a particular way, due to the span expression 564 | /// being evaluated in the context of the procedural macro and the remaining 565 | /// tokens being evaluated in the generated code. 566 | /// 567 | ///
568 | /// 569 | /// # Hygiene 570 | /// 571 | /// Any interpolated tokens preserve the `Span` information provided by their 572 | /// `ToTokens` implementation. Tokens that originate within the `quote_spanned!` 573 | /// invocation are spanned with the given span argument. 574 | /// 575 | ///
576 | /// 577 | /// # Example 578 | /// 579 | /// The following procedural macro code uses `quote_spanned!` to assert that a 580 | /// particular Rust type implements the [`Sync`] trait so that references can be 581 | /// safely shared between threads. 582 | /// 583 | /// ``` 584 | /// # use quote::{quote_spanned, TokenStreamExt, ToTokens}; 585 | /// # use proc_macro2::{Span, TokenStream}; 586 | /// # 587 | /// # struct Type; 588 | /// # 589 | /// # impl Type { 590 | /// # fn span(&self) -> Span { 591 | /// # Span::call_site() 592 | /// # } 593 | /// # } 594 | /// # 595 | /// # impl ToTokens for Type { 596 | /// # fn to_tokens(&self, _tokens: &mut TokenStream) {} 597 | /// # } 598 | /// # 599 | /// # let ty = Type; 600 | /// # let call_site = Span::call_site(); 601 | /// # 602 | /// let ty_span = ty.span(); 603 | /// let assert_sync = quote_spanned! {ty_span=> 604 | /// struct _AssertSync where #ty: Sync; 605 | /// }; 606 | /// ``` 607 | /// 608 | /// If the assertion fails, the user will see an error like the following. The 609 | /// input span of their type is highlighted in the error. 610 | /// 611 | /// ```text 612 | /// error[E0277]: the trait bound `*const (): std::marker::Sync` is not satisfied 613 | /// --> src/main.rs:10:21 614 | /// | 615 | /// 10 | static ref PTR: *const () = &(); 616 | /// | ^^^^^^^^^ `*const ()` cannot be shared between threads safely 617 | /// ``` 618 | /// 619 | /// In this example it is important for the where-clause to be spanned with the 620 | /// line/column information of the user's input type so that error messages are 621 | /// placed appropriately by the compiler. 622 | $quote_spanned 623 | }; 624 | } 625 | 626 | #[cfg(doc)] 627 | __quote_spanned![ 628 | #[macro_export] 629 | macro_rules! quote_spanned { 630 | ($span:expr=> $($tt:tt)*) => { 631 | ... 632 | }; 633 | } 634 | ]; 635 | 636 | #[cfg(not(doc))] 637 | __quote_spanned![ 638 | #[macro_export] 639 | macro_rules! quote_spanned { 640 | ($span:expr=>) => {{ 641 | let _: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); 642 | $crate::__private::TokenStream::new() 643 | }}; 644 | 645 | // Special case rule for a single tt, for performance. 646 | ($span:expr=> $tt:tt) => {{ 647 | let mut _s = $crate::__private::TokenStream::new(); 648 | let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); 649 | $crate::quote_token_spanned!{$tt _s _span} 650 | _s 651 | }}; 652 | 653 | // Special case rules for two tts, for performance. 654 | ($span:expr=> # $var:ident) => {{ 655 | let mut _s = $crate::__private::TokenStream::new(); 656 | let _: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); 657 | $crate::ToTokens::to_tokens(&$var, &mut _s); 658 | _s 659 | }}; 660 | ($span:expr=> $tt1:tt $tt2:tt) => {{ 661 | let mut _s = $crate::__private::TokenStream::new(); 662 | let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); 663 | $crate::quote_token_spanned!{$tt1 _s _span} 664 | $crate::quote_token_spanned!{$tt2 _s _span} 665 | _s 666 | }}; 667 | 668 | // Rule for any other number of tokens. 669 | ($span:expr=> $($tt:tt)*) => {{ 670 | let mut _s = $crate::__private::TokenStream::new(); 671 | let _span: $crate::__private::Span = $crate::__private::get_span($span).__into_span(); 672 | $crate::quote_each_token_spanned!{_s _span $($tt)*} 673 | _s 674 | }}; 675 | } 676 | ]; 677 | 678 | // Extract the names of all #metavariables and pass them to the $call macro. 679 | // 680 | // in: pounded_var_names!(then!(...) a #b c #( #d )* #e) 681 | // out: then!(... b); 682 | // then!(... d); 683 | // then!(... e); 684 | #[macro_export] 685 | #[doc(hidden)] 686 | macro_rules! pounded_var_names { 687 | ($call:ident! $extra:tt $($tts:tt)*) => { 688 | $crate::pounded_var_names_with_context!{$call! $extra 689 | (@ $($tts)*) 690 | ($($tts)* @) 691 | } 692 | }; 693 | } 694 | 695 | #[macro_export] 696 | #[doc(hidden)] 697 | macro_rules! pounded_var_names_with_context { 698 | ($call:ident! $extra:tt ($($b1:tt)*) ($($curr:tt)*)) => { 699 | $( 700 | $crate::pounded_var_with_context!{$call! $extra $b1 $curr} 701 | )* 702 | }; 703 | } 704 | 705 | #[macro_export] 706 | #[doc(hidden)] 707 | macro_rules! pounded_var_with_context { 708 | ($call:ident! $extra:tt $b1:tt ( $($inner:tt)* )) => { 709 | $crate::pounded_var_names!{$call! $extra $($inner)*} 710 | }; 711 | 712 | ($call:ident! $extra:tt $b1:tt [ $($inner:tt)* ]) => { 713 | $crate::pounded_var_names!{$call! $extra $($inner)*} 714 | }; 715 | 716 | ($call:ident! $extra:tt $b1:tt { $($inner:tt)* }) => { 717 | $crate::pounded_var_names!{$call! $extra $($inner)*} 718 | }; 719 | 720 | ($call:ident!($($extra:tt)*) # $var:ident) => { 721 | $crate::$call!($($extra)* $var); 722 | }; 723 | 724 | ($call:ident! $extra:tt $b1:tt $curr:tt) => {}; 725 | } 726 | 727 | #[macro_export] 728 | #[doc(hidden)] 729 | macro_rules! quote_bind_into_iter { 730 | ($has_iter:ident $var:ident) => { 731 | // `mut` may be unused if $var occurs multiple times in the list. 732 | #[allow(unused_mut)] 733 | let (mut $var, i) = $var.quote_into_iter(); 734 | let $has_iter = $has_iter | i; 735 | }; 736 | } 737 | 738 | #[macro_export] 739 | #[doc(hidden)] 740 | macro_rules! quote_bind_next_or_break { 741 | ($var:ident) => { 742 | let $var = match $var.next() { 743 | Some(_x) => $crate::__private::RepInterp(_x), 744 | None => break, 745 | }; 746 | }; 747 | } 748 | 749 | // The obvious way to write this macro is as a tt muncher. This implementation 750 | // does something more complex for two reasons. 751 | // 752 | // - With a tt muncher it's easy to hit Rust's built-in recursion_limit, which 753 | // this implementation avoids because it isn't tail recursive. 754 | // 755 | // - Compile times for a tt muncher are quadratic relative to the length of 756 | // the input. This implementation is linear, so it will be faster 757 | // (potentially much faster) for big inputs. However, the constant factors 758 | // of this implementation are higher than that of a tt muncher, so it is 759 | // somewhat slower than a tt muncher if there are many invocations with 760 | // short inputs. 761 | // 762 | // An invocation like this: 763 | // 764 | // quote_each_token!(_s a b c d e f g h i j); 765 | // 766 | // expands to this: 767 | // 768 | // quote_tokens_with_context!(_s 769 | // (@ @ @ @ @ @ a b c d e f g h i j) 770 | // (@ @ @ @ @ a b c d e f g h i j @) 771 | // (@ @ @ @ a b c d e f g h i j @ @) 772 | // (@ @ @ (a) (b) (c) (d) (e) (f) (g) (h) (i) (j) @ @ @) 773 | // (@ @ a b c d e f g h i j @ @ @ @) 774 | // (@ a b c d e f g h i j @ @ @ @ @) 775 | // (a b c d e f g h i j @ @ @ @ @ @) 776 | // ); 777 | // 778 | // which gets transposed and expanded to this: 779 | // 780 | // quote_token_with_context!(_s @ @ @ @ @ @ a); 781 | // quote_token_with_context!(_s @ @ @ @ @ a b); 782 | // quote_token_with_context!(_s @ @ @ @ a b c); 783 | // quote_token_with_context!(_s @ @ @ (a) b c d); 784 | // quote_token_with_context!(_s @ @ a (b) c d e); 785 | // quote_token_with_context!(_s @ a b (c) d e f); 786 | // quote_token_with_context!(_s a b c (d) e f g); 787 | // quote_token_with_context!(_s b c d (e) f g h); 788 | // quote_token_with_context!(_s c d e (f) g h i); 789 | // quote_token_with_context!(_s d e f (g) h i j); 790 | // quote_token_with_context!(_s e f g (h) i j @); 791 | // quote_token_with_context!(_s f g h (i) j @ @); 792 | // quote_token_with_context!(_s g h i (j) @ @ @); 793 | // quote_token_with_context!(_s h i j @ @ @ @); 794 | // quote_token_with_context!(_s i j @ @ @ @ @); 795 | // quote_token_with_context!(_s j @ @ @ @ @ @); 796 | // 797 | // Without having used muncher-style recursion, we get one invocation of 798 | // quote_token_with_context for each original tt, with three tts of context on 799 | // either side. This is enough for the longest possible interpolation form (a 800 | // repetition with separator, as in `# (#var) , *`) to be fully represented with 801 | // the first or last tt in the middle. 802 | // 803 | // The middle tt (surrounded by parentheses) is the tt being processed. 804 | // 805 | // - When it is a `#`, quote_token_with_context can do an interpolation. The 806 | // interpolation kind will depend on the three subsequent tts. 807 | // 808 | // - When it is within a later part of an interpolation, it can be ignored 809 | // because the interpolation has already been done. 810 | // 811 | // - When it is not part of an interpolation it can be pushed as a single 812 | // token into the output. 813 | // 814 | // - When the middle token is an unparenthesized `@`, that call is one of the 815 | // first 3 or last 3 calls of quote_token_with_context and does not 816 | // correspond to one of the original input tokens, so turns into nothing. 817 | #[macro_export] 818 | #[doc(hidden)] 819 | macro_rules! quote_each_token { 820 | ($tokens:ident $($tts:tt)*) => { 821 | $crate::quote_tokens_with_context!{$tokens 822 | (@ @ @ @ @ @ $($tts)*) 823 | (@ @ @ @ @ $($tts)* @) 824 | (@ @ @ @ $($tts)* @ @) 825 | (@ @ @ $(($tts))* @ @ @) 826 | (@ @ $($tts)* @ @ @ @) 827 | (@ $($tts)* @ @ @ @ @) 828 | ($($tts)* @ @ @ @ @ @) 829 | } 830 | }; 831 | } 832 | 833 | // See the explanation on quote_each_token. 834 | #[macro_export] 835 | #[doc(hidden)] 836 | macro_rules! quote_each_token_spanned { 837 | ($tokens:ident $span:ident $($tts:tt)*) => { 838 | $crate::quote_tokens_with_context_spanned!{$tokens $span 839 | (@ @ @ @ @ @ $($tts)*) 840 | (@ @ @ @ @ $($tts)* @) 841 | (@ @ @ @ $($tts)* @ @) 842 | (@ @ @ $(($tts))* @ @ @) 843 | (@ @ $($tts)* @ @ @ @) 844 | (@ $($tts)* @ @ @ @ @) 845 | ($($tts)* @ @ @ @ @ @) 846 | } 847 | }; 848 | } 849 | 850 | // See the explanation on quote_each_token. 851 | #[macro_export] 852 | #[doc(hidden)] 853 | macro_rules! quote_tokens_with_context { 854 | ($tokens:ident 855 | ($($b3:tt)*) ($($b2:tt)*) ($($b1:tt)*) 856 | ($($curr:tt)*) 857 | ($($a1:tt)*) ($($a2:tt)*) ($($a3:tt)*) 858 | ) => { 859 | $( 860 | $crate::quote_token_with_context!{$tokens $b3 $b2 $b1 $curr $a1 $a2 $a3} 861 | )* 862 | }; 863 | } 864 | 865 | // See the explanation on quote_each_token. 866 | #[macro_export] 867 | #[doc(hidden)] 868 | macro_rules! quote_tokens_with_context_spanned { 869 | ($tokens:ident $span:ident 870 | ($($b3:tt)*) ($($b2:tt)*) ($($b1:tt)*) 871 | ($($curr:tt)*) 872 | ($($a1:tt)*) ($($a2:tt)*) ($($a3:tt)*) 873 | ) => { 874 | $( 875 | $crate::quote_token_with_context_spanned!{$tokens $span $b3 $b2 $b1 $curr $a1 $a2 $a3} 876 | )* 877 | }; 878 | } 879 | 880 | // See the explanation on quote_each_token. 881 | #[macro_export] 882 | #[doc(hidden)] 883 | macro_rules! quote_token_with_context { 884 | // Unparenthesized `@` indicates this call does not correspond to one of the 885 | // original input tokens. Ignore it. 886 | ($tokens:ident $b3:tt $b2:tt $b1:tt @ $a1:tt $a2:tt $a3:tt) => {}; 887 | 888 | // A repetition with no separator. 889 | ($tokens:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) * $a3:tt) => {{ 890 | use $crate::__private::ext::*; 891 | let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; 892 | $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} 893 | let _: $crate::__private::HasIterator = has_iter; 894 | // This is `while true` instead of `loop` because if there are no 895 | // iterators used inside of this repetition then the body would not 896 | // contain any `break`, so the compiler would emit unreachable code 897 | // warnings on anything below the loop. We use has_iter to detect and 898 | // fail to compile when there are no iterators, so here we just work 899 | // around the unneeded extra warning. 900 | while true { 901 | $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} 902 | $crate::quote_each_token!{$tokens $($inner)*} 903 | } 904 | }}; 905 | // ... and one step later. 906 | ($tokens:ident $b3:tt $b2:tt # (( $($inner:tt)* )) * $a2:tt $a3:tt) => {}; 907 | // ... and one step later. 908 | ($tokens:ident $b3:tt # ( $($inner:tt)* ) (*) $a1:tt $a2:tt $a3:tt) => {}; 909 | 910 | // A repetition with separator. 911 | ($tokens:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) $sep:tt *) => {{ 912 | use $crate::__private::ext::*; 913 | let mut _i = 0usize; 914 | let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; 915 | $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} 916 | let _: $crate::__private::HasIterator = has_iter; 917 | while true { 918 | $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} 919 | if _i > 0 { 920 | $crate::quote_token!{$sep $tokens} 921 | } 922 | _i += 1; 923 | $crate::quote_each_token!{$tokens $($inner)*} 924 | } 925 | }}; 926 | // ... and one step later. 927 | ($tokens:ident $b3:tt $b2:tt # (( $($inner:tt)* )) $sep:tt * $a3:tt) => {}; 928 | // ... and one step later. 929 | ($tokens:ident $b3:tt # ( $($inner:tt)* ) ($sep:tt) * $a2:tt $a3:tt) => {}; 930 | // (A special case for `#(var)**`, where the first `*` is treated as the 931 | // repetition symbol and the second `*` is treated as an ordinary token.) 932 | ($tokens:ident # ( $($inner:tt)* ) * (*) $a1:tt $a2:tt $a3:tt) => { 933 | // https://github.com/dtolnay/quote/issues/130 934 | $crate::quote_token!{* $tokens} 935 | }; 936 | // ... and one step later. 937 | ($tokens:ident # ( $($inner:tt)* ) $sep:tt (*) $a1:tt $a2:tt $a3:tt) => {}; 938 | 939 | // A non-repetition interpolation. 940 | ($tokens:ident $b3:tt $b2:tt $b1:tt (#) $var:ident $a2:tt $a3:tt) => { 941 | $crate::ToTokens::to_tokens(&$var, &mut $tokens); 942 | }; 943 | // ... and one step later. 944 | ($tokens:ident $b3:tt $b2:tt # ($var:ident) $a1:tt $a2:tt $a3:tt) => {}; 945 | 946 | // An ordinary token, not part of any interpolation. 947 | ($tokens:ident $b3:tt $b2:tt $b1:tt ($curr:tt) $a1:tt $a2:tt $a3:tt) => { 948 | $crate::quote_token!{$curr $tokens} 949 | }; 950 | } 951 | 952 | // See the explanation on quote_each_token, and on the individual rules of 953 | // quote_token_with_context. 954 | #[macro_export] 955 | #[doc(hidden)] 956 | macro_rules! quote_token_with_context_spanned { 957 | ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt @ $a1:tt $a2:tt $a3:tt) => {}; 958 | 959 | ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) * $a3:tt) => {{ 960 | use $crate::__private::ext::*; 961 | let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; 962 | $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} 963 | let _: $crate::__private::HasIterator = has_iter; 964 | while true { 965 | $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} 966 | $crate::quote_each_token_spanned!{$tokens $span $($inner)*} 967 | } 968 | }}; 969 | ($tokens:ident $span:ident $b3:tt $b2:tt # (( $($inner:tt)* )) * $a2:tt $a3:tt) => {}; 970 | ($tokens:ident $span:ident $b3:tt # ( $($inner:tt)* ) (*) $a1:tt $a2:tt $a3:tt) => {}; 971 | 972 | ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) ( $($inner:tt)* ) $sep:tt *) => {{ 973 | use $crate::__private::ext::*; 974 | let mut _i = 0usize; 975 | let has_iter = $crate::__private::ThereIsNoIteratorInRepetition; 976 | $crate::pounded_var_names!{quote_bind_into_iter!(has_iter) () $($inner)*} 977 | let _: $crate::__private::HasIterator = has_iter; 978 | while true { 979 | $crate::pounded_var_names!{quote_bind_next_or_break!() () $($inner)*} 980 | if _i > 0 { 981 | $crate::quote_token_spanned!{$sep $tokens $span} 982 | } 983 | _i += 1; 984 | $crate::quote_each_token_spanned!{$tokens $span $($inner)*} 985 | } 986 | }}; 987 | ($tokens:ident $span:ident $b3:tt $b2:tt # (( $($inner:tt)* )) $sep:tt * $a3:tt) => {}; 988 | ($tokens:ident $span:ident $b3:tt # ( $($inner:tt)* ) ($sep:tt) * $a2:tt $a3:tt) => {}; 989 | ($tokens:ident $span:ident # ( $($inner:tt)* ) * (*) $a1:tt $a2:tt $a3:tt) => { 990 | // https://github.com/dtolnay/quote/issues/130 991 | $crate::quote_token_spanned!{* $tokens $span} 992 | }; 993 | ($tokens:ident $span:ident # ( $($inner:tt)* ) $sep:tt (*) $a1:tt $a2:tt $a3:tt) => {}; 994 | 995 | ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt (#) $var:ident $a2:tt $a3:tt) => { 996 | $crate::ToTokens::to_tokens(&$var, &mut $tokens); 997 | }; 998 | ($tokens:ident $span:ident $b3:tt $b2:tt # ($var:ident) $a1:tt $a2:tt $a3:tt) => {}; 999 | 1000 | ($tokens:ident $span:ident $b3:tt $b2:tt $b1:tt ($curr:tt) $a1:tt $a2:tt $a3:tt) => { 1001 | $crate::quote_token_spanned!{$curr $tokens $span} 1002 | }; 1003 | } 1004 | 1005 | // These rules are ordered by approximate token frequency, at least for the 1006 | // first 10 or so, to improve compile times. Having `ident` first is by far the 1007 | // most important because it's typically 2-3x more common than the next most 1008 | // common token. 1009 | // 1010 | // Separately, we put the token being matched in the very front so that failing 1011 | // rules may fail to match as quickly as possible. 1012 | #[macro_export] 1013 | #[doc(hidden)] 1014 | macro_rules! quote_token { 1015 | ($ident:ident $tokens:ident) => { 1016 | $crate::__private::push_ident(&mut $tokens, stringify!($ident)); 1017 | }; 1018 | 1019 | (:: $tokens:ident) => { 1020 | $crate::__private::push_colon2(&mut $tokens); 1021 | }; 1022 | 1023 | (( $($inner:tt)* ) $tokens:ident) => { 1024 | $crate::__private::push_group( 1025 | &mut $tokens, 1026 | $crate::__private::Delimiter::Parenthesis, 1027 | $crate::quote!($($inner)*), 1028 | ); 1029 | }; 1030 | 1031 | ([ $($inner:tt)* ] $tokens:ident) => { 1032 | $crate::__private::push_group( 1033 | &mut $tokens, 1034 | $crate::__private::Delimiter::Bracket, 1035 | $crate::quote!($($inner)*), 1036 | ); 1037 | }; 1038 | 1039 | ({ $($inner:tt)* } $tokens:ident) => { 1040 | $crate::__private::push_group( 1041 | &mut $tokens, 1042 | $crate::__private::Delimiter::Brace, 1043 | $crate::quote!($($inner)*), 1044 | ); 1045 | }; 1046 | 1047 | (# $tokens:ident) => { 1048 | $crate::__private::push_pound(&mut $tokens); 1049 | }; 1050 | 1051 | (, $tokens:ident) => { 1052 | $crate::__private::push_comma(&mut $tokens); 1053 | }; 1054 | 1055 | (. $tokens:ident) => { 1056 | $crate::__private::push_dot(&mut $tokens); 1057 | }; 1058 | 1059 | (; $tokens:ident) => { 1060 | $crate::__private::push_semi(&mut $tokens); 1061 | }; 1062 | 1063 | (: $tokens:ident) => { 1064 | $crate::__private::push_colon(&mut $tokens); 1065 | }; 1066 | 1067 | (+ $tokens:ident) => { 1068 | $crate::__private::push_add(&mut $tokens); 1069 | }; 1070 | 1071 | (+= $tokens:ident) => { 1072 | $crate::__private::push_add_eq(&mut $tokens); 1073 | }; 1074 | 1075 | (& $tokens:ident) => { 1076 | $crate::__private::push_and(&mut $tokens); 1077 | }; 1078 | 1079 | (&& $tokens:ident) => { 1080 | $crate::__private::push_and_and(&mut $tokens); 1081 | }; 1082 | 1083 | (&= $tokens:ident) => { 1084 | $crate::__private::push_and_eq(&mut $tokens); 1085 | }; 1086 | 1087 | (@ $tokens:ident) => { 1088 | $crate::__private::push_at(&mut $tokens); 1089 | }; 1090 | 1091 | (! $tokens:ident) => { 1092 | $crate::__private::push_bang(&mut $tokens); 1093 | }; 1094 | 1095 | (^ $tokens:ident) => { 1096 | $crate::__private::push_caret(&mut $tokens); 1097 | }; 1098 | 1099 | (^= $tokens:ident) => { 1100 | $crate::__private::push_caret_eq(&mut $tokens); 1101 | }; 1102 | 1103 | (/ $tokens:ident) => { 1104 | $crate::__private::push_div(&mut $tokens); 1105 | }; 1106 | 1107 | (/= $tokens:ident) => { 1108 | $crate::__private::push_div_eq(&mut $tokens); 1109 | }; 1110 | 1111 | (.. $tokens:ident) => { 1112 | $crate::__private::push_dot2(&mut $tokens); 1113 | }; 1114 | 1115 | (... $tokens:ident) => { 1116 | $crate::__private::push_dot3(&mut $tokens); 1117 | }; 1118 | 1119 | (..= $tokens:ident) => { 1120 | $crate::__private::push_dot_dot_eq(&mut $tokens); 1121 | }; 1122 | 1123 | (= $tokens:ident) => { 1124 | $crate::__private::push_eq(&mut $tokens); 1125 | }; 1126 | 1127 | (== $tokens:ident) => { 1128 | $crate::__private::push_eq_eq(&mut $tokens); 1129 | }; 1130 | 1131 | (>= $tokens:ident) => { 1132 | $crate::__private::push_ge(&mut $tokens); 1133 | }; 1134 | 1135 | (> $tokens:ident) => { 1136 | $crate::__private::push_gt(&mut $tokens); 1137 | }; 1138 | 1139 | (<= $tokens:ident) => { 1140 | $crate::__private::push_le(&mut $tokens); 1141 | }; 1142 | 1143 | (< $tokens:ident) => { 1144 | $crate::__private::push_lt(&mut $tokens); 1145 | }; 1146 | 1147 | (*= $tokens:ident) => { 1148 | $crate::__private::push_mul_eq(&mut $tokens); 1149 | }; 1150 | 1151 | (!= $tokens:ident) => { 1152 | $crate::__private::push_ne(&mut $tokens); 1153 | }; 1154 | 1155 | (| $tokens:ident) => { 1156 | $crate::__private::push_or(&mut $tokens); 1157 | }; 1158 | 1159 | (|= $tokens:ident) => { 1160 | $crate::__private::push_or_eq(&mut $tokens); 1161 | }; 1162 | 1163 | (|| $tokens:ident) => { 1164 | $crate::__private::push_or_or(&mut $tokens); 1165 | }; 1166 | 1167 | (? $tokens:ident) => { 1168 | $crate::__private::push_question(&mut $tokens); 1169 | }; 1170 | 1171 | (-> $tokens:ident) => { 1172 | $crate::__private::push_rarrow(&mut $tokens); 1173 | }; 1174 | 1175 | (<- $tokens:ident) => { 1176 | $crate::__private::push_larrow(&mut $tokens); 1177 | }; 1178 | 1179 | (% $tokens:ident) => { 1180 | $crate::__private::push_rem(&mut $tokens); 1181 | }; 1182 | 1183 | (%= $tokens:ident) => { 1184 | $crate::__private::push_rem_eq(&mut $tokens); 1185 | }; 1186 | 1187 | (=> $tokens:ident) => { 1188 | $crate::__private::push_fat_arrow(&mut $tokens); 1189 | }; 1190 | 1191 | (<< $tokens:ident) => { 1192 | $crate::__private::push_shl(&mut $tokens); 1193 | }; 1194 | 1195 | (<<= $tokens:ident) => { 1196 | $crate::__private::push_shl_eq(&mut $tokens); 1197 | }; 1198 | 1199 | (>> $tokens:ident) => { 1200 | $crate::__private::push_shr(&mut $tokens); 1201 | }; 1202 | 1203 | (>>= $tokens:ident) => { 1204 | $crate::__private::push_shr_eq(&mut $tokens); 1205 | }; 1206 | 1207 | (* $tokens:ident) => { 1208 | $crate::__private::push_star(&mut $tokens); 1209 | }; 1210 | 1211 | (- $tokens:ident) => { 1212 | $crate::__private::push_sub(&mut $tokens); 1213 | }; 1214 | 1215 | (-= $tokens:ident) => { 1216 | $crate::__private::push_sub_eq(&mut $tokens); 1217 | }; 1218 | 1219 | ($lifetime:lifetime $tokens:ident) => { 1220 | $crate::__private::push_lifetime(&mut $tokens, stringify!($lifetime)); 1221 | }; 1222 | 1223 | (_ $tokens:ident) => { 1224 | $crate::__private::push_underscore(&mut $tokens); 1225 | }; 1226 | 1227 | ($other:tt $tokens:ident) => { 1228 | $crate::__private::parse(&mut $tokens, stringify!($other)); 1229 | }; 1230 | } 1231 | 1232 | // See the comment above `quote_token!` about the rule ordering. 1233 | #[macro_export] 1234 | #[doc(hidden)] 1235 | macro_rules! quote_token_spanned { 1236 | ($ident:ident $tokens:ident $span:ident) => { 1237 | $crate::__private::push_ident_spanned(&mut $tokens, $span, stringify!($ident)); 1238 | }; 1239 | 1240 | (:: $tokens:ident $span:ident) => { 1241 | $crate::__private::push_colon2_spanned(&mut $tokens, $span); 1242 | }; 1243 | 1244 | (( $($inner:tt)* ) $tokens:ident $span:ident) => { 1245 | $crate::__private::push_group_spanned( 1246 | &mut $tokens, 1247 | $span, 1248 | $crate::__private::Delimiter::Parenthesis, 1249 | $crate::quote_spanned!($span=> $($inner)*), 1250 | ); 1251 | }; 1252 | 1253 | ([ $($inner:tt)* ] $tokens:ident $span:ident) => { 1254 | $crate::__private::push_group_spanned( 1255 | &mut $tokens, 1256 | $span, 1257 | $crate::__private::Delimiter::Bracket, 1258 | $crate::quote_spanned!($span=> $($inner)*), 1259 | ); 1260 | }; 1261 | 1262 | ({ $($inner:tt)* } $tokens:ident $span:ident) => { 1263 | $crate::__private::push_group_spanned( 1264 | &mut $tokens, 1265 | $span, 1266 | $crate::__private::Delimiter::Brace, 1267 | $crate::quote_spanned!($span=> $($inner)*), 1268 | ); 1269 | }; 1270 | 1271 | (# $tokens:ident $span:ident) => { 1272 | $crate::__private::push_pound_spanned(&mut $tokens, $span); 1273 | }; 1274 | 1275 | (, $tokens:ident $span:ident) => { 1276 | $crate::__private::push_comma_spanned(&mut $tokens, $span); 1277 | }; 1278 | 1279 | (. $tokens:ident $span:ident) => { 1280 | $crate::__private::push_dot_spanned(&mut $tokens, $span); 1281 | }; 1282 | 1283 | (; $tokens:ident $span:ident) => { 1284 | $crate::__private::push_semi_spanned(&mut $tokens, $span); 1285 | }; 1286 | 1287 | (: $tokens:ident $span:ident) => { 1288 | $crate::__private::push_colon_spanned(&mut $tokens, $span); 1289 | }; 1290 | 1291 | (+ $tokens:ident $span:ident) => { 1292 | $crate::__private::push_add_spanned(&mut $tokens, $span); 1293 | }; 1294 | 1295 | (+= $tokens:ident $span:ident) => { 1296 | $crate::__private::push_add_eq_spanned(&mut $tokens, $span); 1297 | }; 1298 | 1299 | (& $tokens:ident $span:ident) => { 1300 | $crate::__private::push_and_spanned(&mut $tokens, $span); 1301 | }; 1302 | 1303 | (&& $tokens:ident $span:ident) => { 1304 | $crate::__private::push_and_and_spanned(&mut $tokens, $span); 1305 | }; 1306 | 1307 | (&= $tokens:ident $span:ident) => { 1308 | $crate::__private::push_and_eq_spanned(&mut $tokens, $span); 1309 | }; 1310 | 1311 | (@ $tokens:ident $span:ident) => { 1312 | $crate::__private::push_at_spanned(&mut $tokens, $span); 1313 | }; 1314 | 1315 | (! $tokens:ident $span:ident) => { 1316 | $crate::__private::push_bang_spanned(&mut $tokens, $span); 1317 | }; 1318 | 1319 | (^ $tokens:ident $span:ident) => { 1320 | $crate::__private::push_caret_spanned(&mut $tokens, $span); 1321 | }; 1322 | 1323 | (^= $tokens:ident $span:ident) => { 1324 | $crate::__private::push_caret_eq_spanned(&mut $tokens, $span); 1325 | }; 1326 | 1327 | (/ $tokens:ident $span:ident) => { 1328 | $crate::__private::push_div_spanned(&mut $tokens, $span); 1329 | }; 1330 | 1331 | (/= $tokens:ident $span:ident) => { 1332 | $crate::__private::push_div_eq_spanned(&mut $tokens, $span); 1333 | }; 1334 | 1335 | (.. $tokens:ident $span:ident) => { 1336 | $crate::__private::push_dot2_spanned(&mut $tokens, $span); 1337 | }; 1338 | 1339 | (... $tokens:ident $span:ident) => { 1340 | $crate::__private::push_dot3_spanned(&mut $tokens, $span); 1341 | }; 1342 | 1343 | (..= $tokens:ident $span:ident) => { 1344 | $crate::__private::push_dot_dot_eq_spanned(&mut $tokens, $span); 1345 | }; 1346 | 1347 | (= $tokens:ident $span:ident) => { 1348 | $crate::__private::push_eq_spanned(&mut $tokens, $span); 1349 | }; 1350 | 1351 | (== $tokens:ident $span:ident) => { 1352 | $crate::__private::push_eq_eq_spanned(&mut $tokens, $span); 1353 | }; 1354 | 1355 | (>= $tokens:ident $span:ident) => { 1356 | $crate::__private::push_ge_spanned(&mut $tokens, $span); 1357 | }; 1358 | 1359 | (> $tokens:ident $span:ident) => { 1360 | $crate::__private::push_gt_spanned(&mut $tokens, $span); 1361 | }; 1362 | 1363 | (<= $tokens:ident $span:ident) => { 1364 | $crate::__private::push_le_spanned(&mut $tokens, $span); 1365 | }; 1366 | 1367 | (< $tokens:ident $span:ident) => { 1368 | $crate::__private::push_lt_spanned(&mut $tokens, $span); 1369 | }; 1370 | 1371 | (*= $tokens:ident $span:ident) => { 1372 | $crate::__private::push_mul_eq_spanned(&mut $tokens, $span); 1373 | }; 1374 | 1375 | (!= $tokens:ident $span:ident) => { 1376 | $crate::__private::push_ne_spanned(&mut $tokens, $span); 1377 | }; 1378 | 1379 | (| $tokens:ident $span:ident) => { 1380 | $crate::__private::push_or_spanned(&mut $tokens, $span); 1381 | }; 1382 | 1383 | (|= $tokens:ident $span:ident) => { 1384 | $crate::__private::push_or_eq_spanned(&mut $tokens, $span); 1385 | }; 1386 | 1387 | (|| $tokens:ident $span:ident) => { 1388 | $crate::__private::push_or_or_spanned(&mut $tokens, $span); 1389 | }; 1390 | 1391 | (? $tokens:ident $span:ident) => { 1392 | $crate::__private::push_question_spanned(&mut $tokens, $span); 1393 | }; 1394 | 1395 | (-> $tokens:ident $span:ident) => { 1396 | $crate::__private::push_rarrow_spanned(&mut $tokens, $span); 1397 | }; 1398 | 1399 | (<- $tokens:ident $span:ident) => { 1400 | $crate::__private::push_larrow_spanned(&mut $tokens, $span); 1401 | }; 1402 | 1403 | (% $tokens:ident $span:ident) => { 1404 | $crate::__private::push_rem_spanned(&mut $tokens, $span); 1405 | }; 1406 | 1407 | (%= $tokens:ident $span:ident) => { 1408 | $crate::__private::push_rem_eq_spanned(&mut $tokens, $span); 1409 | }; 1410 | 1411 | (=> $tokens:ident $span:ident) => { 1412 | $crate::__private::push_fat_arrow_spanned(&mut $tokens, $span); 1413 | }; 1414 | 1415 | (<< $tokens:ident $span:ident) => { 1416 | $crate::__private::push_shl_spanned(&mut $tokens, $span); 1417 | }; 1418 | 1419 | (<<= $tokens:ident $span:ident) => { 1420 | $crate::__private::push_shl_eq_spanned(&mut $tokens, $span); 1421 | }; 1422 | 1423 | (>> $tokens:ident $span:ident) => { 1424 | $crate::__private::push_shr_spanned(&mut $tokens, $span); 1425 | }; 1426 | 1427 | (>>= $tokens:ident $span:ident) => { 1428 | $crate::__private::push_shr_eq_spanned(&mut $tokens, $span); 1429 | }; 1430 | 1431 | (* $tokens:ident $span:ident) => { 1432 | $crate::__private::push_star_spanned(&mut $tokens, $span); 1433 | }; 1434 | 1435 | (- $tokens:ident $span:ident) => { 1436 | $crate::__private::push_sub_spanned(&mut $tokens, $span); 1437 | }; 1438 | 1439 | (-= $tokens:ident $span:ident) => { 1440 | $crate::__private::push_sub_eq_spanned(&mut $tokens, $span); 1441 | }; 1442 | 1443 | ($lifetime:lifetime $tokens:ident $span:ident) => { 1444 | $crate::__private::push_lifetime_spanned(&mut $tokens, $span, stringify!($lifetime)); 1445 | }; 1446 | 1447 | (_ $tokens:ident $span:ident) => { 1448 | $crate::__private::push_underscore_spanned(&mut $tokens, $span); 1449 | }; 1450 | 1451 | ($other:tt $tokens:ident $span:ident) => { 1452 | $crate::__private::parse_spanned(&mut $tokens, $span, stringify!($other)); 1453 | }; 1454 | } 1455 | -------------------------------------------------------------------------------- /src/runtime.rs: -------------------------------------------------------------------------------- 1 | use self::get_span::{GetSpan, GetSpanBase, GetSpanInner}; 2 | use crate::{IdentFragment, ToTokens, TokenStreamExt}; 3 | use core::fmt; 4 | use core::iter; 5 | use core::ops::BitOr; 6 | use proc_macro2::{Group, Ident, Punct, Spacing, TokenTree}; 7 | 8 | #[doc(hidden)] 9 | pub use alloc::format; 10 | #[doc(hidden)] 11 | pub use core::option::Option; 12 | 13 | #[doc(hidden)] 14 | pub type Delimiter = proc_macro2::Delimiter; 15 | #[doc(hidden)] 16 | pub type Span = proc_macro2::Span; 17 | #[doc(hidden)] 18 | pub type TokenStream = proc_macro2::TokenStream; 19 | 20 | #[doc(hidden)] 21 | pub struct HasIterator; // True 22 | #[doc(hidden)] 23 | pub struct ThereIsNoIteratorInRepetition; // False 24 | 25 | impl BitOr for ThereIsNoIteratorInRepetition { 26 | type Output = ThereIsNoIteratorInRepetition; 27 | fn bitor(self, _rhs: ThereIsNoIteratorInRepetition) -> ThereIsNoIteratorInRepetition { 28 | ThereIsNoIteratorInRepetition 29 | } 30 | } 31 | 32 | impl BitOr for HasIterator { 33 | type Output = HasIterator; 34 | fn bitor(self, _rhs: ThereIsNoIteratorInRepetition) -> HasIterator { 35 | HasIterator 36 | } 37 | } 38 | 39 | impl BitOr for ThereIsNoIteratorInRepetition { 40 | type Output = HasIterator; 41 | fn bitor(self, _rhs: HasIterator) -> HasIterator { 42 | HasIterator 43 | } 44 | } 45 | 46 | impl BitOr for HasIterator { 47 | type Output = HasIterator; 48 | fn bitor(self, _rhs: HasIterator) -> HasIterator { 49 | HasIterator 50 | } 51 | } 52 | 53 | /// Extension traits used by the implementation of `quote!`. These are defined 54 | /// in separate traits, rather than as a single trait due to ambiguity issues. 55 | /// 56 | /// These traits expose a `quote_into_iter` method which should allow calling 57 | /// whichever impl happens to be applicable. Calling that method repeatedly on 58 | /// the returned value should be idempotent. 59 | #[doc(hidden)] 60 | pub mod ext { 61 | use super::RepInterp; 62 | use super::{HasIterator as HasIter, ThereIsNoIteratorInRepetition as DoesNotHaveIter}; 63 | use crate::ToTokens; 64 | use alloc::collections::btree_set::{self, BTreeSet}; 65 | use core::slice; 66 | 67 | /// Extension trait providing the `quote_into_iter` method on iterators. 68 | #[doc(hidden)] 69 | pub trait RepIteratorExt: Iterator + Sized { 70 | fn quote_into_iter(self) -> (Self, HasIter) { 71 | (self, HasIter) 72 | } 73 | } 74 | 75 | impl RepIteratorExt for T {} 76 | 77 | /// Extension trait providing the `quote_into_iter` method for 78 | /// non-iterable types. These types interpolate the same value in each 79 | /// iteration of the repetition. 80 | #[doc(hidden)] 81 | pub trait RepToTokensExt { 82 | /// Pretend to be an iterator for the purposes of `quote_into_iter`. 83 | /// This allows repeated calls to `quote_into_iter` to continue 84 | /// correctly returning DoesNotHaveIter. 85 | fn next(&self) -> Option<&Self> { 86 | Some(self) 87 | } 88 | 89 | fn quote_into_iter(&self) -> (&Self, DoesNotHaveIter) { 90 | (self, DoesNotHaveIter) 91 | } 92 | } 93 | 94 | impl RepToTokensExt for T {} 95 | 96 | /// Extension trait providing the `quote_into_iter` method for types that 97 | /// can be referenced as an iterator. 98 | #[doc(hidden)] 99 | pub trait RepAsIteratorExt<'q> { 100 | type Iter: Iterator; 101 | 102 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter); 103 | } 104 | 105 | impl<'q, T: RepAsIteratorExt<'q> + ?Sized> RepAsIteratorExt<'q> for &T { 106 | type Iter = T::Iter; 107 | 108 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 109 | ::quote_into_iter(*self) 110 | } 111 | } 112 | 113 | impl<'q, T: RepAsIteratorExt<'q> + ?Sized> RepAsIteratorExt<'q> for &mut T { 114 | type Iter = T::Iter; 115 | 116 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 117 | ::quote_into_iter(*self) 118 | } 119 | } 120 | 121 | impl<'q, T: 'q> RepAsIteratorExt<'q> for [T] { 122 | type Iter = slice::Iter<'q, T>; 123 | 124 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 125 | (self.iter(), HasIter) 126 | } 127 | } 128 | 129 | impl<'q, T: 'q, const N: usize> RepAsIteratorExt<'q> for [T; N] { 130 | type Iter = slice::Iter<'q, T>; 131 | 132 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 133 | (self.iter(), HasIter) 134 | } 135 | } 136 | 137 | impl<'q, T: 'q> RepAsIteratorExt<'q> for Vec { 138 | type Iter = slice::Iter<'q, T>; 139 | 140 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 141 | (self.iter(), HasIter) 142 | } 143 | } 144 | 145 | impl<'q, T: 'q> RepAsIteratorExt<'q> for BTreeSet { 146 | type Iter = btree_set::Iter<'q, T>; 147 | 148 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 149 | (self.iter(), HasIter) 150 | } 151 | } 152 | 153 | impl<'q, T: RepAsIteratorExt<'q>> RepAsIteratorExt<'q> for RepInterp { 154 | type Iter = T::Iter; 155 | 156 | fn quote_into_iter(&'q self) -> (Self::Iter, HasIter) { 157 | self.0.quote_into_iter() 158 | } 159 | } 160 | } 161 | 162 | // Helper type used within interpolations to allow for repeated binding names. 163 | // Implements the relevant traits, and exports a dummy `next()` method. 164 | #[derive(Copy, Clone)] 165 | #[doc(hidden)] 166 | pub struct RepInterp(pub T); 167 | 168 | impl RepInterp { 169 | // This method is intended to look like `Iterator::next`, and is called when 170 | // a name is bound multiple times, as the previous binding will shadow the 171 | // original `Iterator` object. This allows us to avoid advancing the 172 | // iterator multiple times per iteration. 173 | pub fn next(self) -> Option { 174 | Some(self.0) 175 | } 176 | } 177 | 178 | impl Iterator for RepInterp { 179 | type Item = T::Item; 180 | 181 | fn next(&mut self) -> Option { 182 | self.0.next() 183 | } 184 | } 185 | 186 | impl ToTokens for RepInterp { 187 | fn to_tokens(&self, tokens: &mut TokenStream) { 188 | self.0.to_tokens(tokens); 189 | } 190 | } 191 | 192 | #[doc(hidden)] 193 | #[inline] 194 | pub fn get_span(span: T) -> GetSpan { 195 | GetSpan(GetSpanInner(GetSpanBase(span))) 196 | } 197 | 198 | mod get_span { 199 | use core::ops::Deref; 200 | use proc_macro2::extra::DelimSpan; 201 | use proc_macro2::Span; 202 | 203 | pub struct GetSpan(pub(crate) GetSpanInner); 204 | 205 | pub struct GetSpanInner(pub(crate) GetSpanBase); 206 | 207 | pub struct GetSpanBase(pub(crate) T); 208 | 209 | impl GetSpan { 210 | #[inline] 211 | pub fn __into_span(self) -> Span { 212 | ((self.0).0).0 213 | } 214 | } 215 | 216 | impl GetSpanInner { 217 | #[inline] 218 | pub fn __into_span(&self) -> Span { 219 | (self.0).0.join() 220 | } 221 | } 222 | 223 | impl GetSpanBase { 224 | #[allow(clippy::unused_self)] 225 | pub fn __into_span(&self) -> T { 226 | unreachable!() 227 | } 228 | } 229 | 230 | impl Deref for GetSpan { 231 | type Target = GetSpanInner; 232 | 233 | #[inline] 234 | fn deref(&self) -> &Self::Target { 235 | &self.0 236 | } 237 | } 238 | 239 | impl Deref for GetSpanInner { 240 | type Target = GetSpanBase; 241 | 242 | #[inline] 243 | fn deref(&self) -> &Self::Target { 244 | &self.0 245 | } 246 | } 247 | } 248 | 249 | #[doc(hidden)] 250 | pub fn push_group(tokens: &mut TokenStream, delimiter: Delimiter, inner: TokenStream) { 251 | tokens.append(Group::new(delimiter, inner)); 252 | } 253 | 254 | #[doc(hidden)] 255 | pub fn push_group_spanned( 256 | tokens: &mut TokenStream, 257 | span: Span, 258 | delimiter: Delimiter, 259 | inner: TokenStream, 260 | ) { 261 | let mut g = Group::new(delimiter, inner); 262 | g.set_span(span); 263 | tokens.append(g); 264 | } 265 | 266 | #[doc(hidden)] 267 | pub fn parse(tokens: &mut TokenStream, s: &str) { 268 | let s: TokenStream = s.parse().expect("invalid token stream"); 269 | tokens.extend(iter::once(s)); 270 | } 271 | 272 | #[doc(hidden)] 273 | pub fn parse_spanned(tokens: &mut TokenStream, span: Span, s: &str) { 274 | let s: TokenStream = s.parse().expect("invalid token stream"); 275 | tokens.extend(s.into_iter().map(|t| respan_token_tree(t, span))); 276 | } 277 | 278 | // Token tree with every span replaced by the given one. 279 | fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { 280 | match &mut token { 281 | TokenTree::Group(g) => { 282 | let stream = g 283 | .stream() 284 | .into_iter() 285 | .map(|token| respan_token_tree(token, span)) 286 | .collect(); 287 | *g = Group::new(g.delimiter(), stream); 288 | g.set_span(span); 289 | } 290 | other => other.set_span(span), 291 | } 292 | token 293 | } 294 | 295 | #[doc(hidden)] 296 | pub fn push_ident(tokens: &mut TokenStream, s: &str) { 297 | let span = Span::call_site(); 298 | push_ident_spanned(tokens, span, s); 299 | } 300 | 301 | #[doc(hidden)] 302 | pub fn push_ident_spanned(tokens: &mut TokenStream, span: Span, s: &str) { 303 | tokens.append(ident_maybe_raw(s, span)); 304 | } 305 | 306 | #[doc(hidden)] 307 | pub fn push_lifetime(tokens: &mut TokenStream, lifetime: &str) { 308 | tokens.extend([ 309 | TokenTree::Punct(Punct::new('\'', Spacing::Joint)), 310 | TokenTree::Ident(Ident::new(&lifetime[1..], Span::call_site())), 311 | ]); 312 | } 313 | 314 | #[doc(hidden)] 315 | pub fn push_lifetime_spanned(tokens: &mut TokenStream, span: Span, lifetime: &str) { 316 | tokens.extend([ 317 | TokenTree::Punct({ 318 | let mut apostrophe = Punct::new('\'', Spacing::Joint); 319 | apostrophe.set_span(span); 320 | apostrophe 321 | }), 322 | TokenTree::Ident(Ident::new(&lifetime[1..], span)), 323 | ]); 324 | } 325 | 326 | macro_rules! push_punct { 327 | ($name:ident $spanned:ident $char1:tt) => { 328 | #[doc(hidden)] 329 | pub fn $name(tokens: &mut TokenStream) { 330 | tokens.append(Punct::new($char1, Spacing::Alone)); 331 | } 332 | #[doc(hidden)] 333 | pub fn $spanned(tokens: &mut TokenStream, span: Span) { 334 | let mut punct = Punct::new($char1, Spacing::Alone); 335 | punct.set_span(span); 336 | tokens.append(punct); 337 | } 338 | }; 339 | ($name:ident $spanned:ident $char1:tt $char2:tt) => { 340 | #[doc(hidden)] 341 | pub fn $name(tokens: &mut TokenStream) { 342 | tokens.append(Punct::new($char1, Spacing::Joint)); 343 | tokens.append(Punct::new($char2, Spacing::Alone)); 344 | } 345 | #[doc(hidden)] 346 | pub fn $spanned(tokens: &mut TokenStream, span: Span) { 347 | let mut punct = Punct::new($char1, Spacing::Joint); 348 | punct.set_span(span); 349 | tokens.append(punct); 350 | let mut punct = Punct::new($char2, Spacing::Alone); 351 | punct.set_span(span); 352 | tokens.append(punct); 353 | } 354 | }; 355 | ($name:ident $spanned:ident $char1:tt $char2:tt $char3:tt) => { 356 | #[doc(hidden)] 357 | pub fn $name(tokens: &mut TokenStream) { 358 | tokens.append(Punct::new($char1, Spacing::Joint)); 359 | tokens.append(Punct::new($char2, Spacing::Joint)); 360 | tokens.append(Punct::new($char3, Spacing::Alone)); 361 | } 362 | #[doc(hidden)] 363 | pub fn $spanned(tokens: &mut TokenStream, span: Span) { 364 | let mut punct = Punct::new($char1, Spacing::Joint); 365 | punct.set_span(span); 366 | tokens.append(punct); 367 | let mut punct = Punct::new($char2, Spacing::Joint); 368 | punct.set_span(span); 369 | tokens.append(punct); 370 | let mut punct = Punct::new($char3, Spacing::Alone); 371 | punct.set_span(span); 372 | tokens.append(punct); 373 | } 374 | }; 375 | } 376 | 377 | push_punct!(push_add push_add_spanned '+'); 378 | push_punct!(push_add_eq push_add_eq_spanned '+' '='); 379 | push_punct!(push_and push_and_spanned '&'); 380 | push_punct!(push_and_and push_and_and_spanned '&' '&'); 381 | push_punct!(push_and_eq push_and_eq_spanned '&' '='); 382 | push_punct!(push_at push_at_spanned '@'); 383 | push_punct!(push_bang push_bang_spanned '!'); 384 | push_punct!(push_caret push_caret_spanned '^'); 385 | push_punct!(push_caret_eq push_caret_eq_spanned '^' '='); 386 | push_punct!(push_colon push_colon_spanned ':'); 387 | push_punct!(push_colon2 push_colon2_spanned ':' ':'); 388 | push_punct!(push_comma push_comma_spanned ','); 389 | push_punct!(push_div push_div_spanned '/'); 390 | push_punct!(push_div_eq push_div_eq_spanned '/' '='); 391 | push_punct!(push_dot push_dot_spanned '.'); 392 | push_punct!(push_dot2 push_dot2_spanned '.' '.'); 393 | push_punct!(push_dot3 push_dot3_spanned '.' '.' '.'); 394 | push_punct!(push_dot_dot_eq push_dot_dot_eq_spanned '.' '.' '='); 395 | push_punct!(push_eq push_eq_spanned '='); 396 | push_punct!(push_eq_eq push_eq_eq_spanned '=' '='); 397 | push_punct!(push_ge push_ge_spanned '>' '='); 398 | push_punct!(push_gt push_gt_spanned '>'); 399 | push_punct!(push_le push_le_spanned '<' '='); 400 | push_punct!(push_lt push_lt_spanned '<'); 401 | push_punct!(push_mul_eq push_mul_eq_spanned '*' '='); 402 | push_punct!(push_ne push_ne_spanned '!' '='); 403 | push_punct!(push_or push_or_spanned '|'); 404 | push_punct!(push_or_eq push_or_eq_spanned '|' '='); 405 | push_punct!(push_or_or push_or_or_spanned '|' '|'); 406 | push_punct!(push_pound push_pound_spanned '#'); 407 | push_punct!(push_question push_question_spanned '?'); 408 | push_punct!(push_rarrow push_rarrow_spanned '-' '>'); 409 | push_punct!(push_larrow push_larrow_spanned '<' '-'); 410 | push_punct!(push_rem push_rem_spanned '%'); 411 | push_punct!(push_rem_eq push_rem_eq_spanned '%' '='); 412 | push_punct!(push_fat_arrow push_fat_arrow_spanned '=' '>'); 413 | push_punct!(push_semi push_semi_spanned ';'); 414 | push_punct!(push_shl push_shl_spanned '<' '<'); 415 | push_punct!(push_shl_eq push_shl_eq_spanned '<' '<' '='); 416 | push_punct!(push_shr push_shr_spanned '>' '>'); 417 | push_punct!(push_shr_eq push_shr_eq_spanned '>' '>' '='); 418 | push_punct!(push_star push_star_spanned '*'); 419 | push_punct!(push_sub push_sub_spanned '-'); 420 | push_punct!(push_sub_eq push_sub_eq_spanned '-' '='); 421 | 422 | #[doc(hidden)] 423 | pub fn push_underscore(tokens: &mut TokenStream) { 424 | push_underscore_spanned(tokens, Span::call_site()); 425 | } 426 | 427 | #[doc(hidden)] 428 | pub fn push_underscore_spanned(tokens: &mut TokenStream, span: Span) { 429 | tokens.append(Ident::new("_", span)); 430 | } 431 | 432 | // Helper method for constructing identifiers from the `format_ident!` macro, 433 | // handling `r#` prefixes. 434 | #[doc(hidden)] 435 | pub fn mk_ident(id: &str, span: Option) -> Ident { 436 | let span = span.unwrap_or_else(Span::call_site); 437 | ident_maybe_raw(id, span) 438 | } 439 | 440 | fn ident_maybe_raw(id: &str, span: Span) -> Ident { 441 | if let Some(id) = id.strip_prefix("r#") { 442 | Ident::new_raw(id, span) 443 | } else { 444 | Ident::new(id, span) 445 | } 446 | } 447 | 448 | // Adapts from `IdentFragment` to `fmt::Display` for use by the `format_ident!` 449 | // macro, and exposes span information from these fragments. 450 | // 451 | // This struct also has forwarding implementations of the formatting traits 452 | // `Octal`, `LowerHex`, `UpperHex`, and `Binary` to allow for their use within 453 | // `format_ident!`. 454 | #[derive(Copy, Clone)] 455 | #[doc(hidden)] 456 | pub struct IdentFragmentAdapter(pub T); 457 | 458 | impl IdentFragmentAdapter { 459 | pub fn span(&self) -> Option { 460 | self.0.span() 461 | } 462 | } 463 | 464 | impl fmt::Display for IdentFragmentAdapter { 465 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 466 | IdentFragment::fmt(&self.0, f) 467 | } 468 | } 469 | 470 | impl fmt::Octal for IdentFragmentAdapter { 471 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 472 | fmt::Octal::fmt(&self.0, f) 473 | } 474 | } 475 | 476 | impl fmt::LowerHex for IdentFragmentAdapter { 477 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 478 | fmt::LowerHex::fmt(&self.0, f) 479 | } 480 | } 481 | 482 | impl fmt::UpperHex for IdentFragmentAdapter { 483 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 484 | fmt::UpperHex::fmt(&self.0, f) 485 | } 486 | } 487 | 488 | impl fmt::Binary for IdentFragmentAdapter { 489 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 490 | fmt::Binary::fmt(&self.0, f) 491 | } 492 | } 493 | -------------------------------------------------------------------------------- /src/spanned.rs: -------------------------------------------------------------------------------- 1 | use crate::ToTokens; 2 | use proc_macro2::extra::DelimSpan; 3 | use proc_macro2::{Span, TokenStream}; 4 | 5 | // Not public API other than via the syn crate. Use syn::spanned::Spanned. 6 | pub trait Spanned: private::Sealed { 7 | fn __span(&self) -> Span; 8 | } 9 | 10 | impl Spanned for Span { 11 | fn __span(&self) -> Span { 12 | *self 13 | } 14 | } 15 | 16 | impl Spanned for DelimSpan { 17 | fn __span(&self) -> Span { 18 | self.join() 19 | } 20 | } 21 | 22 | impl Spanned for T { 23 | fn __span(&self) -> Span { 24 | join_spans(self.into_token_stream()) 25 | } 26 | } 27 | 28 | fn join_spans(tokens: TokenStream) -> Span { 29 | let mut iter = tokens.into_iter().map(|tt| tt.span()); 30 | 31 | let first = match iter.next() { 32 | Some(span) => span, 33 | None => return Span::call_site(), 34 | }; 35 | 36 | iter.fold(None, |_prev, next| Some(next)) 37 | .and_then(|last| first.join(last)) 38 | .unwrap_or(first) 39 | } 40 | 41 | mod private { 42 | use crate::ToTokens; 43 | use proc_macro2::extra::DelimSpan; 44 | use proc_macro2::Span; 45 | 46 | pub trait Sealed {} 47 | impl Sealed for Span {} 48 | impl Sealed for DelimSpan {} 49 | impl Sealed for T {} 50 | } 51 | -------------------------------------------------------------------------------- /src/to_tokens.rs: -------------------------------------------------------------------------------- 1 | use super::TokenStreamExt; 2 | use alloc::borrow::Cow; 3 | use alloc::rc::Rc; 4 | use core::iter; 5 | use proc_macro2::{Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; 6 | use std::ffi::{CStr, CString}; 7 | 8 | /// Types that can be interpolated inside a `quote!` invocation. 9 | pub trait ToTokens { 10 | /// Write `self` to the given `TokenStream`. 11 | /// 12 | /// The token append methods provided by the [`TokenStreamExt`] extension 13 | /// trait may be useful for implementing `ToTokens`. 14 | /// 15 | /// # Example 16 | /// 17 | /// Example implementation for a struct representing Rust paths like 18 | /// `std::cmp::PartialEq`: 19 | /// 20 | /// ``` 21 | /// use proc_macro2::{TokenTree, Spacing, Span, Punct, TokenStream}; 22 | /// use quote::{TokenStreamExt, ToTokens}; 23 | /// 24 | /// pub struct Path { 25 | /// pub global: bool, 26 | /// pub segments: Vec, 27 | /// } 28 | /// 29 | /// impl ToTokens for Path { 30 | /// fn to_tokens(&self, tokens: &mut TokenStream) { 31 | /// for (i, segment) in self.segments.iter().enumerate() { 32 | /// if i > 0 || self.global { 33 | /// // Double colon `::` 34 | /// tokens.append(Punct::new(':', Spacing::Joint)); 35 | /// tokens.append(Punct::new(':', Spacing::Alone)); 36 | /// } 37 | /// segment.to_tokens(tokens); 38 | /// } 39 | /// } 40 | /// } 41 | /// # 42 | /// # pub struct PathSegment; 43 | /// # 44 | /// # impl ToTokens for PathSegment { 45 | /// # fn to_tokens(&self, tokens: &mut TokenStream) { 46 | /// # unimplemented!() 47 | /// # } 48 | /// # } 49 | /// ``` 50 | fn to_tokens(&self, tokens: &mut TokenStream); 51 | 52 | /// Convert `self` directly into a `TokenStream` object. 53 | /// 54 | /// This method is implicitly implemented using `to_tokens`, and acts as a 55 | /// convenience method for consumers of the `ToTokens` trait. 56 | fn to_token_stream(&self) -> TokenStream { 57 | let mut tokens = TokenStream::new(); 58 | self.to_tokens(&mut tokens); 59 | tokens 60 | } 61 | 62 | /// Convert `self` directly into a `TokenStream` object. 63 | /// 64 | /// This method is implicitly implemented using `to_tokens`, and acts as a 65 | /// convenience method for consumers of the `ToTokens` trait. 66 | fn into_token_stream(self) -> TokenStream 67 | where 68 | Self: Sized, 69 | { 70 | self.to_token_stream() 71 | } 72 | } 73 | 74 | impl ToTokens for &T { 75 | fn to_tokens(&self, tokens: &mut TokenStream) { 76 | (**self).to_tokens(tokens); 77 | } 78 | } 79 | 80 | impl ToTokens for &mut T { 81 | fn to_tokens(&self, tokens: &mut TokenStream) { 82 | (**self).to_tokens(tokens); 83 | } 84 | } 85 | 86 | impl<'a, T: ?Sized + ToOwned + ToTokens> ToTokens for Cow<'a, T> { 87 | fn to_tokens(&self, tokens: &mut TokenStream) { 88 | (**self).to_tokens(tokens); 89 | } 90 | } 91 | 92 | impl ToTokens for Box { 93 | fn to_tokens(&self, tokens: &mut TokenStream) { 94 | (**self).to_tokens(tokens); 95 | } 96 | } 97 | 98 | impl ToTokens for Rc { 99 | fn to_tokens(&self, tokens: &mut TokenStream) { 100 | (**self).to_tokens(tokens); 101 | } 102 | } 103 | 104 | impl ToTokens for Option { 105 | fn to_tokens(&self, tokens: &mut TokenStream) { 106 | if let Some(t) = self { 107 | t.to_tokens(tokens); 108 | } 109 | } 110 | } 111 | 112 | impl ToTokens for str { 113 | fn to_tokens(&self, tokens: &mut TokenStream) { 114 | tokens.append(Literal::string(self)); 115 | } 116 | } 117 | 118 | impl ToTokens for String { 119 | fn to_tokens(&self, tokens: &mut TokenStream) { 120 | self.as_str().to_tokens(tokens); 121 | } 122 | } 123 | 124 | impl ToTokens for i8 { 125 | fn to_tokens(&self, tokens: &mut TokenStream) { 126 | tokens.append(Literal::i8_suffixed(*self)); 127 | } 128 | } 129 | 130 | impl ToTokens for i16 { 131 | fn to_tokens(&self, tokens: &mut TokenStream) { 132 | tokens.append(Literal::i16_suffixed(*self)); 133 | } 134 | } 135 | 136 | impl ToTokens for i32 { 137 | fn to_tokens(&self, tokens: &mut TokenStream) { 138 | tokens.append(Literal::i32_suffixed(*self)); 139 | } 140 | } 141 | 142 | impl ToTokens for i64 { 143 | fn to_tokens(&self, tokens: &mut TokenStream) { 144 | tokens.append(Literal::i64_suffixed(*self)); 145 | } 146 | } 147 | 148 | impl ToTokens for i128 { 149 | fn to_tokens(&self, tokens: &mut TokenStream) { 150 | tokens.append(Literal::i128_suffixed(*self)); 151 | } 152 | } 153 | 154 | impl ToTokens for isize { 155 | fn to_tokens(&self, tokens: &mut TokenStream) { 156 | tokens.append(Literal::isize_suffixed(*self)); 157 | } 158 | } 159 | 160 | impl ToTokens for u8 { 161 | fn to_tokens(&self, tokens: &mut TokenStream) { 162 | tokens.append(Literal::u8_suffixed(*self)); 163 | } 164 | } 165 | 166 | impl ToTokens for u16 { 167 | fn to_tokens(&self, tokens: &mut TokenStream) { 168 | tokens.append(Literal::u16_suffixed(*self)); 169 | } 170 | } 171 | 172 | impl ToTokens for u32 { 173 | fn to_tokens(&self, tokens: &mut TokenStream) { 174 | tokens.append(Literal::u32_suffixed(*self)); 175 | } 176 | } 177 | 178 | impl ToTokens for u64 { 179 | fn to_tokens(&self, tokens: &mut TokenStream) { 180 | tokens.append(Literal::u64_suffixed(*self)); 181 | } 182 | } 183 | 184 | impl ToTokens for u128 { 185 | fn to_tokens(&self, tokens: &mut TokenStream) { 186 | tokens.append(Literal::u128_suffixed(*self)); 187 | } 188 | } 189 | 190 | impl ToTokens for usize { 191 | fn to_tokens(&self, tokens: &mut TokenStream) { 192 | tokens.append(Literal::usize_suffixed(*self)); 193 | } 194 | } 195 | 196 | impl ToTokens for f32 { 197 | fn to_tokens(&self, tokens: &mut TokenStream) { 198 | tokens.append(Literal::f32_suffixed(*self)); 199 | } 200 | } 201 | 202 | impl ToTokens for f64 { 203 | fn to_tokens(&self, tokens: &mut TokenStream) { 204 | tokens.append(Literal::f64_suffixed(*self)); 205 | } 206 | } 207 | 208 | impl ToTokens for char { 209 | fn to_tokens(&self, tokens: &mut TokenStream) { 210 | tokens.append(Literal::character(*self)); 211 | } 212 | } 213 | 214 | impl ToTokens for bool { 215 | fn to_tokens(&self, tokens: &mut TokenStream) { 216 | let word = if *self { "true" } else { "false" }; 217 | tokens.append(Ident::new(word, Span::call_site())); 218 | } 219 | } 220 | 221 | impl ToTokens for CStr { 222 | fn to_tokens(&self, tokens: &mut TokenStream) { 223 | tokens.append(Literal::c_string(self)); 224 | } 225 | } 226 | 227 | impl ToTokens for CString { 228 | fn to_tokens(&self, tokens: &mut TokenStream) { 229 | tokens.append(Literal::c_string(self)); 230 | } 231 | } 232 | 233 | impl ToTokens for Group { 234 | fn to_tokens(&self, tokens: &mut TokenStream) { 235 | tokens.append(self.clone()); 236 | } 237 | } 238 | 239 | impl ToTokens for Ident { 240 | fn to_tokens(&self, tokens: &mut TokenStream) { 241 | tokens.append(self.clone()); 242 | } 243 | } 244 | 245 | impl ToTokens for Punct { 246 | fn to_tokens(&self, tokens: &mut TokenStream) { 247 | tokens.append(self.clone()); 248 | } 249 | } 250 | 251 | impl ToTokens for Literal { 252 | fn to_tokens(&self, tokens: &mut TokenStream) { 253 | tokens.append(self.clone()); 254 | } 255 | } 256 | 257 | impl ToTokens for TokenTree { 258 | fn to_tokens(&self, tokens: &mut TokenStream) { 259 | tokens.append(self.clone()); 260 | } 261 | } 262 | 263 | impl ToTokens for TokenStream { 264 | fn to_tokens(&self, tokens: &mut TokenStream) { 265 | tokens.extend(iter::once(self.clone())); 266 | } 267 | 268 | fn into_token_stream(self) -> TokenStream { 269 | self 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /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::disallowed_names, 3 | clippy::let_underscore_untyped, 4 | clippy::shadow_unrelated, 5 | clippy::unseparated_literal_suffix, 6 | clippy::used_underscore_binding 7 | )] 8 | 9 | extern crate proc_macro; 10 | 11 | use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream}; 12 | use quote::{format_ident, quote, quote_spanned, TokenStreamExt}; 13 | use std::borrow::Cow; 14 | use std::collections::BTreeSet; 15 | use std::ffi::{CStr, CString}; 16 | 17 | struct X; 18 | 19 | impl quote::ToTokens for X { 20 | fn to_tokens(&self, tokens: &mut TokenStream) { 21 | tokens.append(Ident::new("X", Span::call_site())); 22 | } 23 | } 24 | 25 | #[test] 26 | fn test_quote_impl() { 27 | let tokens = quote! { 28 | impl<'a, T: ToTokens> ToTokens for &'a T { 29 | fn to_tokens(&self, tokens: &mut TokenStream) { 30 | (**self).to_tokens(tokens) 31 | } 32 | } 33 | }; 34 | 35 | let expected = concat!( 36 | "impl < 'a , T : ToTokens > ToTokens for & 'a T { ", 37 | "fn to_tokens (& self , tokens : & mut TokenStream) { ", 38 | "(* * self) . to_tokens (tokens) ", 39 | "} ", 40 | "}" 41 | ); 42 | 43 | assert_eq!(expected, tokens.to_string()); 44 | } 45 | 46 | #[test] 47 | fn test_quote_spanned_impl() { 48 | let span = Span::call_site(); 49 | let tokens = quote_spanned! {span=> 50 | impl<'a, T: ToTokens> ToTokens for &'a T { 51 | fn to_tokens(&self, tokens: &mut TokenStream) { 52 | (**self).to_tokens(tokens) 53 | } 54 | } 55 | }; 56 | 57 | let expected = concat!( 58 | "impl < 'a , T : ToTokens > ToTokens for & 'a T { ", 59 | "fn to_tokens (& self , tokens : & mut TokenStream) { ", 60 | "(* * self) . to_tokens (tokens) ", 61 | "} ", 62 | "}" 63 | ); 64 | 65 | assert_eq!(expected, tokens.to_string()); 66 | } 67 | 68 | #[test] 69 | fn test_substitution() { 70 | let x = X; 71 | let tokens = quote!(#x <#x> (#x) [#x] {#x}); 72 | 73 | let expected = "X < X > (X) [X] { X }"; 74 | 75 | assert_eq!(expected, tokens.to_string()); 76 | } 77 | 78 | #[test] 79 | fn test_iter() { 80 | let primes = &[X, X, X, X]; 81 | 82 | assert_eq!("X X X X", quote!(#(#primes)*).to_string()); 83 | 84 | assert_eq!("X , X , X , X ,", quote!(#(#primes,)*).to_string()); 85 | 86 | assert_eq!("X , X , X , X", quote!(#(#primes),*).to_string()); 87 | } 88 | 89 | #[test] 90 | fn test_array() { 91 | let array: [u8; 40] = [0; 40]; 92 | let _ = quote!(#(#array #array)*); 93 | 94 | let ref_array: &[u8; 40] = &[0; 40]; 95 | let _ = quote!(#(#ref_array #ref_array)*); 96 | 97 | let ref_slice: &[u8] = &[0; 40]; 98 | let _ = quote!(#(#ref_slice #ref_slice)*); 99 | 100 | let array: [X; 2] = [X, X]; // !Copy 101 | let _ = quote!(#(#array #array)*); 102 | 103 | let ref_array: &[X; 2] = &[X, X]; 104 | let _ = quote!(#(#ref_array #ref_array)*); 105 | 106 | let ref_slice: &[X] = &[X, X]; 107 | let _ = quote!(#(#ref_slice #ref_slice)*); 108 | 109 | let array_of_array: [[u8; 2]; 2] = [[0; 2]; 2]; 110 | let _ = quote!(#(#(#array_of_array)*)*); 111 | } 112 | 113 | #[test] 114 | fn test_advanced() { 115 | let generics = quote!( <'a, T> ); 116 | 117 | let where_clause = quote!( where T: Serialize ); 118 | 119 | let field_ty = quote!(String); 120 | 121 | let item_ty = quote!(Cow<'a, str>); 122 | 123 | let path = quote!(SomeTrait::serialize_with); 124 | 125 | let value = quote!(self.x); 126 | 127 | let tokens = quote! { 128 | struct SerializeWith #generics #where_clause { 129 | value: &'a #field_ty, 130 | phantom: ::std::marker::PhantomData<#item_ty>, 131 | } 132 | 133 | impl #generics ::serde::Serialize for SerializeWith #generics #where_clause { 134 | fn serialize(&self, s: &mut S) -> Result<(), S::Error> 135 | where S: ::serde::Serializer 136 | { 137 | #path(self.value, s) 138 | } 139 | } 140 | 141 | SerializeWith { 142 | value: #value, 143 | phantom: ::std::marker::PhantomData::<#item_ty>, 144 | } 145 | }; 146 | 147 | let expected = concat!( 148 | "struct SerializeWith < 'a , T > where T : Serialize { ", 149 | "value : & 'a String , ", 150 | "phantom : :: std :: marker :: PhantomData < Cow < 'a , str > > , ", 151 | "} ", 152 | "impl < 'a , T > :: serde :: Serialize for SerializeWith < 'a , T > where T : Serialize { ", 153 | "fn serialize < S > (& self , s : & mut S) -> Result < () , S :: Error > ", 154 | "where S : :: serde :: Serializer ", 155 | "{ ", 156 | "SomeTrait :: serialize_with (self . value , s) ", 157 | "} ", 158 | "} ", 159 | "SerializeWith { ", 160 | "value : self . x , ", 161 | "phantom : :: std :: marker :: PhantomData :: < Cow < 'a , str > > , ", 162 | "}" 163 | ); 164 | 165 | assert_eq!(expected, tokens.to_string()); 166 | } 167 | 168 | #[test] 169 | fn test_integer() { 170 | let ii8 = -1i8; 171 | let ii16 = -1i16; 172 | let ii32 = -1i32; 173 | let ii64 = -1i64; 174 | let ii128 = -1i128; 175 | let iisize = -1isize; 176 | let uu8 = 1u8; 177 | let uu16 = 1u16; 178 | let uu32 = 1u32; 179 | let uu64 = 1u64; 180 | let uu128 = 1u128; 181 | let uusize = 1usize; 182 | 183 | let tokens = quote! { 184 | 1 1i32 1u256 185 | #ii8 #ii16 #ii32 #ii64 #ii128 #iisize 186 | #uu8 #uu16 #uu32 #uu64 #uu128 #uusize 187 | }; 188 | let expected = 189 | "1 1i32 1u256 - 1i8 - 1i16 - 1i32 - 1i64 - 1i128 - 1isize 1u8 1u16 1u32 1u64 1u128 1usize"; 190 | assert_eq!(expected, tokens.to_string()); 191 | } 192 | 193 | #[test] 194 | fn test_floating() { 195 | let e32 = 2.345f32; 196 | 197 | let e64 = 2.345f64; 198 | 199 | let tokens = quote! { 200 | #e32 201 | #e64 202 | }; 203 | let expected = "2.345f32 2.345f64"; 204 | assert_eq!(expected, tokens.to_string()); 205 | } 206 | 207 | #[test] 208 | fn test_char() { 209 | let zero = '\u{1}'; 210 | let pound = '#'; 211 | let quote = '"'; 212 | let apost = '\''; 213 | let newline = '\n'; 214 | let heart = '\u{2764}'; 215 | 216 | let tokens = quote! { 217 | #zero #pound #quote #apost #newline #heart 218 | }; 219 | let expected = "'\\u{1}' '#' '\"' '\\'' '\\n' '\u{2764}'"; 220 | assert_eq!(expected, tokens.to_string()); 221 | } 222 | 223 | #[test] 224 | fn test_str() { 225 | let s = "\u{1} a 'b \" c"; 226 | let tokens = quote!(#s); 227 | let expected = "\"\\u{1} a 'b \\\" c\""; 228 | assert_eq!(expected, tokens.to_string()); 229 | } 230 | 231 | #[test] 232 | fn test_string() { 233 | let s = "\u{1} a 'b \" c".to_string(); 234 | let tokens = quote!(#s); 235 | let expected = "\"\\u{1} a 'b \\\" c\""; 236 | assert_eq!(expected, tokens.to_string()); 237 | } 238 | 239 | #[test] 240 | fn test_c_str() { 241 | let s = CStr::from_bytes_with_nul(b"\x01 a 'b \" c\0").unwrap(); 242 | let tokens = quote!(#s); 243 | let expected = "c\"\\u{1} a 'b \\\" c\""; 244 | assert_eq!(expected, tokens.to_string()); 245 | } 246 | 247 | #[test] 248 | fn test_c_string() { 249 | let s = CString::new(&b"\x01 a 'b \" c"[..]).unwrap(); 250 | let tokens = quote!(#s); 251 | let expected = "c\"\\u{1} a 'b \\\" c\""; 252 | assert_eq!(expected, tokens.to_string()); 253 | } 254 | 255 | #[test] 256 | fn test_interpolated_literal() { 257 | macro_rules! m { 258 | ($literal:literal) => { 259 | quote!($literal) 260 | }; 261 | } 262 | 263 | let tokens = m!(1); 264 | let expected = "1"; 265 | assert_eq!(expected, tokens.to_string()); 266 | 267 | let tokens = m!(-1); 268 | let expected = "- 1"; 269 | assert_eq!(expected, tokens.to_string()); 270 | 271 | let tokens = m!(true); 272 | let expected = "true"; 273 | assert_eq!(expected, tokens.to_string()); 274 | 275 | let tokens = m!(-true); 276 | let expected = "- true"; 277 | assert_eq!(expected, tokens.to_string()); 278 | } 279 | 280 | #[test] 281 | fn test_ident() { 282 | let foo = Ident::new("Foo", Span::call_site()); 283 | let bar = Ident::new(&format!("Bar{}", 7), Span::call_site()); 284 | let tokens = quote!(struct #foo; enum #bar {}); 285 | let expected = "struct Foo ; enum Bar7 { }"; 286 | assert_eq!(expected, tokens.to_string()); 287 | } 288 | 289 | #[test] 290 | fn test_underscore() { 291 | let tokens = quote!(let _;); 292 | let expected = "let _ ;"; 293 | assert_eq!(expected, tokens.to_string()); 294 | } 295 | 296 | #[test] 297 | fn test_duplicate() { 298 | let ch = 'x'; 299 | 300 | let tokens = quote!(#ch #ch); 301 | 302 | let expected = "'x' 'x'"; 303 | assert_eq!(expected, tokens.to_string()); 304 | } 305 | 306 | #[test] 307 | fn test_fancy_repetition() { 308 | let foo = vec!["a", "b"]; 309 | let bar = vec![true, false]; 310 | 311 | let tokens = quote! { 312 | #(#foo: #bar),* 313 | }; 314 | 315 | let expected = r#""a" : true , "b" : false"#; 316 | assert_eq!(expected, tokens.to_string()); 317 | } 318 | 319 | #[test] 320 | fn test_nested_fancy_repetition() { 321 | let nested = vec![vec!['a', 'b', 'c'], vec!['x', 'y', 'z']]; 322 | 323 | let tokens = quote! { 324 | #( 325 | #(#nested)* 326 | ),* 327 | }; 328 | 329 | let expected = "'a' 'b' 'c' , 'x' 'y' 'z'"; 330 | assert_eq!(expected, tokens.to_string()); 331 | } 332 | 333 | #[test] 334 | fn test_duplicate_name_repetition() { 335 | let foo = &["a", "b"]; 336 | 337 | let tokens = quote! { 338 | #(#foo: #foo),* 339 | #(#foo: #foo),* 340 | }; 341 | 342 | let expected = r#""a" : "a" , "b" : "b" "a" : "a" , "b" : "b""#; 343 | assert_eq!(expected, tokens.to_string()); 344 | } 345 | 346 | #[test] 347 | fn test_duplicate_name_repetition_no_copy() { 348 | let foo = vec!["a".to_owned(), "b".to_owned()]; 349 | 350 | let tokens = quote! { 351 | #(#foo: #foo),* 352 | }; 353 | 354 | let expected = r#""a" : "a" , "b" : "b""#; 355 | assert_eq!(expected, tokens.to_string()); 356 | } 357 | 358 | #[test] 359 | fn test_btreeset_repetition() { 360 | let mut set = BTreeSet::new(); 361 | set.insert("a".to_owned()); 362 | set.insert("b".to_owned()); 363 | 364 | let tokens = quote! { 365 | #(#set: #set),* 366 | }; 367 | 368 | let expected = r#""a" : "a" , "b" : "b""#; 369 | assert_eq!(expected, tokens.to_string()); 370 | } 371 | 372 | #[test] 373 | fn test_variable_name_conflict() { 374 | // The implementation of `#(...),*` uses the variable `_i` but it should be 375 | // fine, if a little confusing when debugging. 376 | let _i = vec!['a', 'b']; 377 | let tokens = quote! { #(#_i),* }; 378 | let expected = "'a' , 'b'"; 379 | assert_eq!(expected, tokens.to_string()); 380 | } 381 | 382 | #[test] 383 | fn test_nonrep_in_repetition() { 384 | let rep = vec!["a", "b"]; 385 | let nonrep = "c"; 386 | 387 | let tokens = quote! { 388 | #(#rep #rep : #nonrep #nonrep),* 389 | }; 390 | 391 | let expected = r#""a" "a" : "c" "c" , "b" "b" : "c" "c""#; 392 | assert_eq!(expected, tokens.to_string()); 393 | } 394 | 395 | #[test] 396 | fn test_empty_quote() { 397 | let tokens = quote!(); 398 | assert_eq!("", tokens.to_string()); 399 | } 400 | 401 | #[test] 402 | fn test_box_str() { 403 | let b = "str".to_owned().into_boxed_str(); 404 | let tokens = quote! { #b }; 405 | assert_eq!("\"str\"", tokens.to_string()); 406 | } 407 | 408 | #[test] 409 | fn test_cow() { 410 | let owned: Cow = Cow::Owned(Ident::new("owned", Span::call_site())); 411 | 412 | let ident = Ident::new("borrowed", Span::call_site()); 413 | let borrowed = Cow::Borrowed(&ident); 414 | 415 | let tokens = quote! { #owned #borrowed }; 416 | assert_eq!("owned borrowed", tokens.to_string()); 417 | } 418 | 419 | #[test] 420 | fn test_closure() { 421 | fn field_i(i: usize) -> Ident { 422 | format_ident!("__field{}", i) 423 | } 424 | 425 | let fields = (0usize..3) 426 | .map(field_i as fn(_) -> _) 427 | .map(|var| quote! { #var }); 428 | 429 | let tokens = quote! { #(#fields)* }; 430 | assert_eq!("__field0 __field1 __field2", tokens.to_string()); 431 | } 432 | 433 | #[test] 434 | fn test_append_tokens() { 435 | let mut a = quote!(a); 436 | let b = quote!(b); 437 | a.append_all(b); 438 | assert_eq!("a b", a.to_string()); 439 | } 440 | 441 | #[test] 442 | fn test_format_ident() { 443 | let id0 = format_ident!("Aa"); 444 | let id1 = format_ident!("Hello{x}", x = id0); 445 | let id2 = format_ident!("Hello{x}", x = 5usize); 446 | let id3 = format_ident!("Hello{}_{x}", id0, x = 10usize); 447 | let id4 = format_ident!("Aa", span = Span::call_site()); 448 | let id5 = format_ident!("Hello{}", Cow::Borrowed("World")); 449 | 450 | assert_eq!(id0, "Aa"); 451 | assert_eq!(id1, "HelloAa"); 452 | assert_eq!(id2, "Hello5"); 453 | assert_eq!(id3, "HelloAa_10"); 454 | assert_eq!(id4, "Aa"); 455 | assert_eq!(id5, "HelloWorld"); 456 | } 457 | 458 | #[test] 459 | fn test_format_ident_strip_raw() { 460 | let id = format_ident!("r#struct"); 461 | let my_id = format_ident!("MyId{}", id); 462 | let raw_my_id = format_ident!("r#MyId{}", id); 463 | 464 | assert_eq!(id, "r#struct"); 465 | assert_eq!(my_id, "MyIdstruct"); 466 | assert_eq!(raw_my_id, "r#MyIdstruct"); 467 | } 468 | 469 | #[test] 470 | fn test_outer_line_comment() { 471 | let tokens = quote! { 472 | /// doc 473 | }; 474 | let expected = "# [doc = r\" doc\"]"; 475 | assert_eq!(expected, tokens.to_string()); 476 | } 477 | 478 | #[test] 479 | fn test_inner_line_comment() { 480 | let tokens = quote! { 481 | //! doc 482 | }; 483 | let expected = "# ! [doc = r\" doc\"]"; 484 | assert_eq!(expected, tokens.to_string()); 485 | } 486 | 487 | #[test] 488 | fn test_outer_block_comment() { 489 | let tokens = quote! { 490 | /** doc */ 491 | }; 492 | let expected = "# [doc = r\" doc \"]"; 493 | assert_eq!(expected, tokens.to_string()); 494 | } 495 | 496 | #[test] 497 | fn test_inner_block_comment() { 498 | let tokens = quote! { 499 | /*! doc */ 500 | }; 501 | let expected = "# ! [doc = r\" doc \"]"; 502 | assert_eq!(expected, tokens.to_string()); 503 | } 504 | 505 | #[test] 506 | fn test_outer_attr() { 507 | let tokens = quote! { 508 | #[inline] 509 | }; 510 | let expected = "# [inline]"; 511 | assert_eq!(expected, tokens.to_string()); 512 | } 513 | 514 | #[test] 515 | fn test_inner_attr() { 516 | let tokens = quote! { 517 | #![no_std] 518 | }; 519 | let expected = "# ! [no_std]"; 520 | assert_eq!(expected, tokens.to_string()); 521 | } 522 | 523 | // https://github.com/dtolnay/quote/issues/130 524 | #[test] 525 | fn test_star_after_repetition() { 526 | let c = vec!['0', '1']; 527 | let tokens = quote! { 528 | #( 529 | f(#c); 530 | )* 531 | *out = None; 532 | }; 533 | let expected = "f ('0') ; f ('1') ; * out = None ;"; 534 | assert_eq!(expected, tokens.to_string()); 535 | } 536 | 537 | #[test] 538 | fn test_quote_raw_id() { 539 | let id = quote!(r#raw_id); 540 | assert_eq!(id.to_string(), "r#raw_id"); 541 | } 542 | 543 | #[test] 544 | fn test_type_inference_for_span() { 545 | trait CallSite { 546 | fn get() -> Self; 547 | } 548 | 549 | impl CallSite for Span { 550 | fn get() -> Self { 551 | Span::call_site() 552 | } 553 | } 554 | 555 | let span = Span::call_site(); 556 | let _ = quote_spanned!(span=> ...); 557 | 558 | let delim_span = Group::new(Delimiter::Parenthesis, TokenStream::new()).delim_span(); 559 | let _ = quote_spanned!(delim_span=> ...); 560 | 561 | let inferred = CallSite::get(); 562 | let _ = quote_spanned!(inferred=> ...); 563 | 564 | if false { 565 | let proc_macro_span = proc_macro::Span::call_site(); 566 | let _ = quote_spanned!(proc_macro_span.into()=> ...); 567 | } 568 | } 569 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-interpolated-dup.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | fn main() { 4 | let nonrep = ""; 5 | 6 | // Without some protection against repetitions with no iterator somewhere 7 | // inside, this would loop infinitely. 8 | quote!(#(#nonrep #nonrep)*); 9 | } 10 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-interpolated-dup.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> tests/ui/does-not-have-iter-interpolated-dup.rs:8:5 3 | | 4 | 8 | quote!(#(#nonrep #nonrep)*); 5 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | | | 7 | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` 8 | | expected due to this 9 | | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` 10 | | 11 | = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 12 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-interpolated.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | fn main() { 4 | let nonrep = ""; 5 | 6 | // Without some protection against repetitions with no iterator somewhere 7 | // inside, this would loop infinitely. 8 | quote!(#(#nonrep)*); 9 | } 10 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-interpolated.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> tests/ui/does-not-have-iter-interpolated.rs:8:5 3 | | 4 | 8 | quote!(#(#nonrep)*); 5 | | ^^^^^^^^^^^^^^^^^^^ 6 | | | 7 | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` 8 | | expected due to this 9 | | here the type of `has_iter` is inferred to be `ThereIsNoIteratorInRepetition` 10 | | 11 | = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 12 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-separated.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | fn main() { 4 | quote!(#(a b),*); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter-separated.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> tests/ui/does-not-have-iter-separated.rs:4:5 3 | | 4 | 4 | quote!(#(a b),*); 5 | | ^^^^^^^^^^^^^^^^ 6 | | | 7 | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` 8 | | expected due to this 9 | | 10 | = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 11 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | fn main() { 4 | quote!(#(a b)*); 5 | } 6 | -------------------------------------------------------------------------------- /tests/ui/does-not-have-iter.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> tests/ui/does-not-have-iter.rs:4:5 3 | | 4 | 4 | quote!(#(a b)*); 5 | | ^^^^^^^^^^^^^^^ 6 | | | 7 | | expected `HasIterator`, found `ThereIsNoIteratorInRepetition` 8 | | expected due to this 9 | | 10 | = note: this error originates in the macro `$crate::quote_token_with_context` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 11 | -------------------------------------------------------------------------------- /tests/ui/not-quotable.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | use std::net::Ipv4Addr; 3 | 4 | fn main() { 5 | let ip = Ipv4Addr::LOCALHOST; 6 | let _ = quote! { #ip }; 7 | } 8 | -------------------------------------------------------------------------------- /tests/ui/not-quotable.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `Ipv4Addr: ToTokens` is not satisfied 2 | --> tests/ui/not-quotable.rs:6:13 3 | | 4 | 6 | let _ = quote! { #ip }; 5 | | ^^^^^^^^^^^^^^ 6 | | | 7 | | the trait `ToTokens` is not implemented for `Ipv4Addr` 8 | | required by a bound introduced by this call 9 | | 10 | = help: the following other types implement trait `ToTokens`: 11 | &T 12 | &mut T 13 | Box 14 | CStr 15 | CString 16 | Cow<'a, T> 17 | Option 18 | Rc 19 | and $N others 20 | = note: this error originates in the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 21 | -------------------------------------------------------------------------------- /tests/ui/not-repeatable.rs: -------------------------------------------------------------------------------- 1 | use quote::quote; 2 | 3 | struct Ipv4Addr; 4 | 5 | fn main() { 6 | let ip = Ipv4Addr; 7 | let _ = quote! { #(#ip)* }; 8 | } 9 | -------------------------------------------------------------------------------- /tests/ui/not-repeatable.stderr: -------------------------------------------------------------------------------- 1 | error[E0599]: the method `quote_into_iter` exists for struct `Ipv4Addr`, but its trait bounds were not satisfied 2 | --> tests/ui/not-repeatable.rs:7:13 3 | | 4 | 3 | struct Ipv4Addr; 5 | | --------------- method `quote_into_iter` not found for this struct because it doesn't satisfy `Ipv4Addr: Iterator`, `Ipv4Addr: ToTokens`, `Ipv4Addr: ext::RepIteratorExt` or `Ipv4Addr: ext::RepToTokensExt` 6 | ... 7 | 7 | let _ = quote! { #(#ip)* }; 8 | | ^^^^^^^^^^^^^^^^^^ method cannot be called on `Ipv4Addr` due to unsatisfied trait bounds 9 | | 10 | = note: the following trait bounds were not satisfied: 11 | `Ipv4Addr: Iterator` 12 | which is required by `Ipv4Addr: ext::RepIteratorExt` 13 | `&Ipv4Addr: Iterator` 14 | which is required by `&Ipv4Addr: ext::RepIteratorExt` 15 | `Ipv4Addr: ToTokens` 16 | which is required by `Ipv4Addr: ext::RepToTokensExt` 17 | `&mut Ipv4Addr: Iterator` 18 | which is required by `&mut Ipv4Addr: ext::RepIteratorExt` 19 | note: the traits `Iterator` and `ToTokens` must be implemented 20 | --> src/to_tokens.rs 21 | | 22 | | pub trait ToTokens { 23 | | ^^^^^^^^^^^^^^^^^^ 24 | | 25 | ::: $RUST/core/src/iter/traits/iterator.rs 26 | | 27 | | pub trait Iterator { 28 | | ^^^^^^^^^^^^^^^^^^ 29 | = help: items from traits can only be used if the trait is implemented and in scope 30 | = note: the following traits define an item `quote_into_iter`, perhaps you need to implement one of them: 31 | candidate #1: `ext::RepAsIteratorExt` 32 | candidate #2: `ext::RepIteratorExt` 33 | candidate #3: `ext::RepToTokensExt` 34 | = note: this error originates in the macro `$crate::quote_bind_into_iter` which comes from the expansion of the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) 35 | -------------------------------------------------------------------------------- /tests/ui/wrong-type-span.rs: -------------------------------------------------------------------------------- 1 | use quote::quote_spanned; 2 | 3 | fn main() { 4 | let span = ""; 5 | let x = 0i32; 6 | quote_spanned!(span=> #x); 7 | } 8 | -------------------------------------------------------------------------------- /tests/ui/wrong-type-span.stderr: -------------------------------------------------------------------------------- 1 | error[E0308]: mismatched types 2 | --> tests/ui/wrong-type-span.rs:6:5 3 | | 4 | 6 | quote_spanned!(span=> #x); 5 | | ^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | | | 7 | | expected `Span`, found `&str` 8 | | expected due to this 9 | | 10 | = note: this error originates in the macro `quote_spanned` (in Nightly builds, run with -Z macro-backtrace for more info) 11 | --------------------------------------------------------------------------------