macro_rules_attribute-0.2.2/.cargo_vcs_info.json0000644000000001360000000000100154330ustar { "git": { "sha1": "cc800f99c893bf2f8abdeb225d3b51edc382da4c" }, "path_in_vcs": "" }macro_rules_attribute-0.2.2/.github/workflows/CI.yml000064400000000000000000000055001046102023000206360ustar 00000000000000name: CI on: push: branches: - master pull_request: jobs: # == CHECK == # check: name: "Check beta stable and MSRV=1.78.0" runs-on: ubuntu-latest strategy: matrix: rust-toolchains: - 1.78.0 - stable - beta cargo-locked: ["--locked", ""] steps: - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust-toolchains }} override: true - name: Clone repo uses: actions/checkout@v2 - name: Update `Cargo.lock` if: matrix.cargo-locked != '--locked' run: cargo update -v - name: Cargo check uses: actions-rs/cargo@v1 with: command: check args: ${{ matrix.cargo-locked }} # == BUILD & TEST == # test: name: Build and test runs-on: ${{ matrix.os }} needs: [check] strategy: fail-fast: false matrix: os: - ubuntu-latest - macos-latest - windows-latest rust-toolchains: - 1.78.0 - stable steps: - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: profile: default override: true toolchain: ${{ matrix.rust-toolchains }} - name: Clone repo uses: actions/checkout@v2 - name: Cargo test uses: actions-rs/cargo@v1 env: RUSTDOCFLAGS: '-Zcrate-attr=feature(macro_attributes_in_derive_output)' RUSTFLAGS: '-Zcrate-attr=feature(macro_attributes_in_derive_output)' RUSTC_BOOTSTRAP: '1' with: command: test - name: Cargo test (embedded doc tests) if: matrix.rust-toolchains == 'stable' uses: actions-rs/cargo@v1 env: RUSTC_BOOTSTRAP: 1 with: command: test args: --features better-docs --doc # # == UI TESTS == # ui-test: # name: UI Tests # runs-on: ubuntu-latest # needs: [check] # steps: # - name: Install Rust toolchain # uses: actions-rs/toolchain@v1 # with: # profile: default # override: true # toolchain: stable # - name: Clone repo # uses: actions/checkout@v2 # - name: Cargo UI test # uses: actions-rs/cargo@v1 # with: # command: test-ui required-jobs: name: 'All the required jobs' needs: - check - test runs-on: ubuntu-latest if: ${{ always() }} steps: - name: 'Check success of the required jobs' run: | RESULT=$(echo "${{ join(needs.*.result, '') }}" | sed -e "s/success//g") if [ -n "$RESULT" ]; then echo "❌" false fi echo "✅" macro_rules_attribute-0.2.2/.github/workflows/future-proof.yml000064400000000000000000000027021046102023000230010ustar 00000000000000# Templated by `cargo-generate` using https://github.com/danielhenrymantilla/proc-macro-template name: Cron CI on: push: branches: - master schedule: - cron: '0 8 * * 1,5' jobs: # == TEST == # test-no-ui: name: (Check & Build &) Test runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: - ubuntu-latest - macos-latest - windows-latest rust-toolchains: - 1.78.0 - stable - beta - nightly cargo-locked: ["--locked", ""] steps: - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: profile: default override: true toolchain: ${{ matrix.rust-toolchains }} - name: Clone repo uses: actions/checkout@v2 - name: Update `Cargo.lock` if: matrix.cargo-locked != '--locked' run: cargo update -v - name: Cargo test uses: actions-rs/cargo@v1 env: RUSTDOCFLAGS: '-Zcrate-attr=feature(macro_attributes_in_derive_output)' RUSTFLAGS: '-Zcrate-attr=feature(macro_attributes_in_derive_output)' RUSTC_BOOTSTRAP: '1' with: command: test args: ${{ matrix.cargo-locked }} # - name: Cargo test (embed `README.md` + UI) # if: matrix.rust-toolchains != '1.78.0' # uses: actions-rs/cargo@v1 # with: # command: test-ui macro_rules_attribute-0.2.2/.gitignore000064400000000000000000000000231046102023000162060ustar 00000000000000/target **/*.rs.bk macro_rules_attribute-0.2.2/Cargo.toml0000644000000031330000000000100134310ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "macro_rules_attribute" version = "0.2.2" authors = ["Daniel Henry-Mantilla "] exclude = ["*.sh"] description = "Use declarative macros in attribute or derive position" homepage = "https://crates.io/crates/macro_rules_attribute" documentation = "https://docs.rs/macro_rules_attribute" readme = "README.md" keywords = [ "macro", "attribute", "decorator", "derive", "macro_rules", ] categories = ["rust-patterns"] license = "Apache-2.0 OR MIT OR Zlib" repository = "https://github.com/danielhenrymantilla/macro_rules_attribute-rs" [package.metadata.docs.rs] features = ["better-docs"] rustdoc-args = [ "--html-before-content", "fix-docsrs-li-details-summary.html", ] [dependencies.macro_rules_attribute-proc_macro] version = "=0.2.2" [dependencies.paste] version = "1.0.7" [dev-dependencies.once_cell] version = "1.10.0" [dev-dependencies.pin-project-lite] version = "0.2.8" [dev-dependencies.serde] version = "1.0.136" features = ["derive"] [features] better-docs = [] default = [] verbose-expansions = ["macro_rules_attribute-proc_macro/verbose-expansions"] macro_rules_attribute-0.2.2/Cargo.toml.orig000064400000000000000000000023001046102023000171050ustar 00000000000000[package] name = "macro_rules_attribute" version = "0.2.2" # Keep in sync authors = ["Daniel Henry-Mantilla "] edition = "2018" documentation = "https://docs.rs/macro_rules_attribute" homepage = "https://crates.io/crates/macro_rules_attribute" repository = "https://github.com/danielhenrymantilla/macro_rules_attribute-rs" description = "Use declarative macros in attribute or derive position" keywords = ["macro", "attribute", "decorator", "derive", "macro_rules"] categories = ["rust-patterns"] license = "Apache-2.0 OR MIT OR Zlib" readme = "README.md" exclude = ["*.sh"] [dependencies] paste.version = "1.0.7" [dependencies.macro_rules_attribute-proc_macro] version = "=0.2.2" # Keep in sync path = "src/proc_macro" [features] default = [] better-docs = [] verbose-expansions = [ "macro_rules_attribute-proc_macro/verbose-expansions", ] [dev-dependencies] once_cell.version = "1.10.0" pin-project-lite.version = "0.2.8" serde.version = "1.0.136" serde.features = ["derive"] [package.metadata.docs.rs] features = [ "better-docs", ] rustdoc-args = [ "--html-before-content", "fix-docsrs-li-details-summary.html", ] [workspace] members = ["src/proc_macro"] macro_rules_attribute-0.2.2/LICENSE-APACHE000064400000000000000000000261711046102023000161560ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 Daniel Henry-Mantilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. macro_rules_attribute-0.2.2/LICENSE-MIT000064400000000000000000000021301046102023000156530ustar 00000000000000MIT License Copyright (c) 2019 Daniel Henry-Mantilla Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. macro_rules_attribute-0.2.2/LICENSE-ZLIB000064400000000000000000000016031046102023000157660ustar 00000000000000zlib License (C) 2019 Daniel Henry-Mantilla This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. macro_rules_attribute-0.2.2/README.md000064400000000000000000000255271046102023000155150ustar 00000000000000# `::macro_rules_attribute` Use declarative macros in attribute or derive position. ```rust ,ignore macro_rules! my_fancy_decorator { /* … */ } #[apply(my_fancy_decorator!)] struct Foo { /* … */ } ``` ```rust ,ignore macro_rules! MyFancyDerive { /* … */ } #[derive(MyFancyDerive!)] /* using this crate's `#[derive]` attribute */ struct Foo { /* … */ } ``` [![Repository](https://img.shields.io/badge/repository-GitHub-brightgreen.svg)]( https://github.com/danielhenrymantilla/macro_rules_attribute-rs) [![Latest version](https://img.shields.io/crates/v/macro_rules_attribute.svg)]( https://crates.io/crates/macro_rules_attribute) [![Documentation](https://docs.rs/macro_rules_attribute/badge.svg)]( https://docs.rs/macro_rules_attribute) [![MSRV](https://img.shields.io/badge/MSRV-1.78.0-white)]( https://gist.github.com/danielhenrymantilla/9b59de4db8e5f2467ed008b3c450527b) [![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)]( https://github.com/rust-secure-code/safety-dance/) [![License](https://img.shields.io/crates/l/macro_rules_attribute.svg)]( https://github.com/danielhenrymantilla/macro_rules_attribute-rs/blob/master/LICENSE-ZLIB) [![CI](https://github.com/danielhenrymantilla/macro_rules_attribute-rs/workflows/CI/badge.svg)]( https://github.com/danielhenrymantilla/macro_rules_attribute-rs/actions) ## Motivation
Click to see `macro_rules!` macros can be extremely powerful, but their call-site ergonomics are sometimes not great, especially when decorating item definitions. Indeed, compare: ```rust ,ignore foo! { struct Struct { some_field: SomeType, } } ``` to: ```rust ,ignore #[foo] struct Struct { some_field: SomeType, } ``` 1. The former does not scale well, since it leads to **rightward drift and "excessive" braces**. 1. But on the other hand, the latter requires setting up a dedicated crate for the compiler, a `proc-macro` crate. And 99% of the time this will pull the [`::syn`] and [`::quote`] dependencies, which have **a non-negligible compile-time overhead** (the first time they are compiled). - note: these crates are a wonderful piece of technology, and can lead to extremely powerful macros. When the logic of the macro is so complicated that it requires a recursive `tt` muncher when implemented as a `macro_rules!` macro, it is definitely time to be using a `proc`edural macro. Anything involving `ident` generation / derivation, for instance, will very often require `proc`edural macros, unless it is simple enough for [`::paste`] to handle it. ___ ## Solution
With this crate's #\[[apply]\] and #\[[derive]\] attributes, it is now possible to use `proc_macro_attribute` syntax to apply a `macro_rules!` macro: ```rust #[macro_use] extern crate macro_rules_attribute; macro_rules! foo { // … # ( $($tt:tt)* ) => () } macro_rules! Bar { // … # ( $($tt:tt)* ) => () } #[apply(foo)] #[derive(Debug, Bar!)] struct Struct { some_field: SomeType, } # # fn main() {} ``` without even depending on [`::quote`], [`::syn`] or [`::proc-macro2`], for **fast compile times**. [`::paste`]: https://docs.rs/paste [`::proc-macro2`]: https://docs.rs/proc_macro2 [`::syn`]: https://docs.rs/syn [`::quote`]: https://docs.rs/quote [`::pin-project`]: https://docs.rs/pin-project [`::pin-project-lite`]: https://docs.rs/pin-project-lite # Examples
Click to see ### Nicer derives ```rust #[macro_use] extern crate macro_rules_attribute; // Easily define shorthand aliases for "derive groups" derive_alias! { #[derive(Eq!)] = #[derive(Eq, PartialEq)]; #[derive(Ord!)] = #[derive(Ord, PartialOrd, Eq!)]; #[derive(Copy!)] = #[derive(Copy, Clone)]; #[derive(StdDerives!)] = #[derive(Debug, Copy!, Default, Ord!, Hash)]; } /// Strongly-typed newtype wrapper around a `usize`, to be used for `PlayerId`s. #[derive(StdDerives!, Into!, From!)] pub struct PlayerId /* = */ ( pub usize, ); // You can also fully define your own derives using `macro_rules!` syntax // (handling generic type definitions may be the only finicky thing, though…) macro_rules! Into {( $( #[$attr:meta] )* $pub:vis struct $NewType:ident ( $(#[$field_attr:meta])* $field_pub:vis $Inner:ty $(, $($rest:tt)* )? ); ) => ( impl ::core::convert::Into<$Inner> for $NewType { #[inline] fn into (self: $NewType) -> $Inner { self.0 } } )} use Into; macro_rules! From {( $( #[$attr:meta] )* $pub:vis struct $NewType:ident ( $(#[$field_attr:meta])* $field_pub:vis $Inner:ty $(, $(#[$other_field_attr:meta])* $other_field_pub:vis $Rest:ty )* $(,)? ); ) => ( impl ::core::convert::From<$Inner> for $NewType { #[inline] fn from (inner: $Inner) -> Self { Self(inner, $($Rest::default),*) } } )} use From; # # fn main() {} ``` ### Have a `-lite` version of a proc-macro dependency that thus requires unergonomic `macro_rules!`? Say you are writing a (pervasive and yet) tiny dependency within the `async` ecosystem. - By virtue of working with `async`, you'll most probably need to deal with pin-projections, and thence, with [`::pin-project`]. - But by virtue of being (pervasive and yet) tiny, you don't want to depend on the `quote / proc-macro2 / syn` heavyweight[^only_full_syn_is_heavy] troika/trinity/triumvirate of more advanced proc-macro crates. [^only_full_syn_is_heavy]: (note that only `syn` with the `"full"` features would be the truly heavyweight party) Hence why you may reach for something such as [`::pin-project-lite`], and its `pin_project!` `macro_rules!`-based polyfill of the former's `#[pin_project]` attribute. But this suddenly hinders the ergonomics of your type definitions, and, worse, would not be composable whenever the pattern were to be repeated for some other functionality (_e.g._, say a `cell_project!` similar macro). Say no more! Time to #\[[apply]\] our neat trick: ```rust #[macro_use] extern crate macro_rules_attribute; use { ::core::pin::{ Pin, }, ::pin_project_lite::{ pin_project, }, }; #[apply(pin_project!)] struct Struct { #[pin] pinned: T, unpinned: U, } impl Struct { fn method(self: Pin<&mut Self>) { let this = self.project(); let _: Pin<&mut T> = this.pinned; // Pinned reference to the field let _: &mut U = this.unpinned; // Normal reference to the field } } # # fn main() {} ``` ### More ergonomic `lazy_static!`s Say you had something like: ```rust # use Sync as Logic; # static MY_GLOBAL: &dyn Logic = &Vec::::new(); ``` and now you want to change the value of that `MY_GLOBAL` to something that isn't `const`-constructible, and yet would like to minimize the churn in doing so. ```rust ,compile_fail // (For those unaware of it, leaking memory to initialize a lazy static is // a completely fine pattern, since it only occurs once, and thus, a bounded // amount of times). static MY_GLOBAL: &dyn Logic = Box::leak(Box::new(vec![42, 27])); // Error: not `const`! ``` You could _directly_ use a `lazy_static!` or a `OnceCell`, but then the definition of your `static` will now appear noisier than it needs be. It's time for attribute-position polish! First, define the helper around, say, `OnceCell`'s `Lazy` type: ```rust macro_rules! lazy_init {( $( #[$attrs:meta] )* $pub:vis static $NAME:ident: $Ty:ty = $init_value:expr ; ) => ( $( #[$attrs] )* $pub static $NAME : ::once_cell::sync::Lazy<$Ty> = ::once_cell::sync::Lazy::new(|| $init_value) ; )} pub(in crate) use lazy_init; ``` and now it is time to use it!: ```rust # use Sync as Logic; # #[macro_use] extern crate macro_rules_attribute; #[apply(lazy_init)] static MY_GLOBAL: &dyn Logic = Box::leak(Box::new(vec![42, 27])); # # macro_rules! lazy_init {( # $( #[$attrs:meta] )* # $pub:vis # static $NAME:ident : $Ty:ty = $init_value:expr ; # ) => ( # $( #[$attrs] )* # $pub # static $NAME : ::once_cell::sync::Lazy<$Ty> = # ::once_cell::sync::Lazy::new(|| $init_value) # ; # )} use lazy_init; # # fn main() {} ```
# Debugging An optional compilation feature, `"verbose-expansions"` can be used to print at compile-time the exact output of each macro invocation from this crate: ```toml [dependencies] macro_rules_attribute.version = "..." macro_rules_attribute.features = ["verbose-expansions"] ``` # Features ### `derive` aliases ```rust # fn main() {} #[macro_use] extern crate macro_rules_attribute; derive_alias! { #[derive(Ord!)] = #[derive(PartialEq, Eq, PartialOrd, Ord)]; } #[derive(Debug, Clone, Copy, Ord!)] struct Foo { // … } ``` - See [`derive_alias!`] and #\[[derive]\] for more info. ### `cfg` aliases
Click to see ```rust # fn main() {} #[macro_use] extern crate macro_rules_attribute; attribute_alias! { #[apply(complex_cfg!)] = #[cfg( any( any( foo, feature = "bar", ), all( target_os = "fenestrations", not(target_arch = "Pear"), ), ), )]; } #[apply(complex_cfg!)] mod some_item { /* … */ } ```
### Not using `#[macro_use] extern crate macro_rules_attribute`
Click to see If you are allergic to `#[macro_use]` unscoped / globally-preluded semantics, you may not be fond of having to use: ```rust #[macro_use] extern crate macro_rules_attribute; # fn main() {} ``` like this documentation pervasively does. In that case, know that you may very well stick to using `use` imports: ```rust use ::macro_rules_attribute::{derive, derive_alias, /* … */}; // or even use ::macro_rules_attribute::*; derive_alias! { #[derive(Copy!)] = #[derive(Clone, Copy)]; } #[derive(Copy!)] struct Foo; ``` or even inlining the fully qualified paths (but note that the `…_alias!` macros still take unqualified paths inside the definitions): ```rust ::macro_rules_attribute::derive_alias! { #[derive(Copy!)] = #[derive(Clone, Copy)]; } #[::macro_rules_attribute::derive(Copy!)] struct Foo; ``` I personally find these approaches too noisy to be worth it, despite the so gained "namespace purity", hence my not using that pattern across the rest of the examples.
[apply]: https://docs.rs/macro_rules_attribute/0.1.*/macro_rules_attribute/attr.apply.html [derive]: https://docs.rs/macro_rules_attribute/0.1.*/macro_rules_attribute/attr.derive.html [`derive_alias!`]: https://docs.rs/macro_rules_attribute/0.1.*/macro_rules_attribute/macro.derive_alias.html macro_rules_attribute-0.2.2/fix-docsrs-li-details-summary.html000064400000000000000000000000651046102023000227130ustar 00000000000000 macro_rules_attribute-0.2.2/rust-toolchain.toml000064400000000000000000000002001046102023000200630ustar 00000000000000[toolchain] channel = '1.78.0' # Templated by `cargo-generate` using https://github.com/danielhenrymantilla/proc-macro-template macro_rules_attribute-0.2.2/src/lib.rs000064400000000000000000000361221046102023000161320ustar 00000000000000/*! [apply]: apply [derive]: derive [`derive_alias!`]: derive_alias [`macro_rules_attribute`]: macro_rules_attribute [`macro_rules_derive`]: macro_rules_derive */ #![cfg_attr(feature = "better-docs", cfg_attr(all(), doc = include_str!("../README.md")) )] #![cfg_attr(feature = "better-docs", feature(doc_auto_cfg), )] #![no_std] #![forbid(unsafe_code)] /// Legacy name for what is currently named #\[[apply]] /// /// Despite being a slightly clearer name (than `#[apply]` is) w.r.t. what it /// does, `#[macro_rules_attribute]` had the big drawback of being a mouthful. /// /// Hence the `#[apply]` alias being born, and now even superseding /// `#[macro_rules_attribute]` altogether as the author-deemed "idiomatic" /// name to favor. pub use ::macro_rules_attribute_proc_macro::macro_rules_attribute; /// Applies the given `macro_rules!` macro to the decorated item. /// /// This, as with any `proc_macro_attribute`, **consumes** the item it /// decorates: it is the `macro_rules!` macro job to generate it (_it is thus /// able to modify it_!). /// /// For a version with "read-only" access to the item it decorates, see /// [`macro_rules_derive`][`macro@macro_rules_derive`]. /// /// ## Examples /// /// ### Deriving getters for a (non-generic) `struct` /// /// Imagine having define the following handy `make_getters!` (`macro_rules!`) /// macro: /// /** ```rust macro_rules! make_getters {( $(#[$struct_meta:meta])* $struct_vis:vis struct $StructName:ident { $( $(#[$field_meta:meta])* $field_vis:vis // this visibility will be applied to the getters instead $field_name:ident : $field_ty:ty ),* $(,)? } ) => ( // First, generate the struct definition we have been given, but with // private fields instead. $(#[$struct_meta])* $struct_vis struct $StructName { $( $(#[$field_meta])* // notice the lack of visibility => private fields $field_name: $field_ty, )* } // Then, implement the getters: impl $StructName { $( #[inline] $field_vis fn $field_name (self: &'_ Self) -> &'_ $field_ty { &self.$field_name } )* } )} ``` */ /// /// Basically allowing you to write: /// /** ```rust ,compile_fail use example::Person; mod example { make_getters! { /// The macro handles meta attributes such as docstrings pub struct Person { pub name: String, pub age: u8, } } } fn is_new_born (person: &'_ mut Person) -> bool { // Reading the value through the getter is fine… return *person.age() == 0; // But trying to mutate it by skipping the getter is not 💪 person.age = 0; // ^ error[E0616]: field `age` of struct `example::Person` is private } ``` */ /// /// This is fine, _etc._, but that rightward drift on `make_getters! {` syntax /// problematic: /// /// - Incurs in extra rightward drift and thus, noise. /// /// - Worse, **it leads to a non-escalable / composable pattern**: if we had a /// second macro, say `make_setters!`, our syntax is unable to handle both /// macros being called on the same type definition. /// /// Hence `::macro_rules_attribute`'s #\[[apply]\] (formerly called /// `#[macro_rules_attribute]` itself) helper: /// /** ```rust # fn main () {} #[macro_use] extern crate macro_rules_attribute; use example::Person; mod example { #[apply(make_getters!)] // or `#[apply(make_getters)]`: the final `!` is not mandatory /// The macro handles meta attributes such as docstrings pub struct Person { pub name: String, pub age: u8, } # // where; # macro_rules! make_getters {( # $(#[$struct_meta:meta])* # $struct_vis:vis # struct $StructName:ident { # $( # $(#[$field_meta:meta])* # $field_vis:vis // this visibility will be applied to the getters instead # $field_name:ident : $field_ty:ty # ),* $(,)? # } # ) => ( # // First, generate the struct definition we have been given, but with # // private fields instead. # $(#[$struct_meta])* # $struct_vis # struct $StructName { # $( # $(#[$field_meta])* # // notice the lack of visibility => private fields # $field_name: $field_ty, # )* # } # // Then, implement the getters: # impl $StructName { # $( # #[inline] # $field_vis # fn $field_name (self: &'_ Self) # -> &'_ $field_ty # { # &self.$field_name # } # )* # } # )} use make_getters; } fn is_new_born (person: &'_ Person) -> bool { // Reading the value through the getter is fine… *person.age() == 0 // But trying to mutate it by skipping the getter is not 💪 // person.age == 0 // ^ error[E0616]: field `age` of struct `example::Person` is private } ``` */ pub use ::macro_rules_attribute_proc_macro::macro_rules_attribute as apply; /// Applies the given `macro_rules!` macro to the decorated item. /// /// This, as with any `#[derive(...)]`, **does not consume** the item it /// decorates: instead, it only generates code on top of it. /// /// Also derives [`Custom`] to allow using `#[custom(...)]` and `#[derive_args(...)]` /// as derive helpers. /// /// ## Examples /// /// ### Implementing `Into` for a given `#[repr(Int)]` `enum`: /// /** ```rust #[macro_use] extern crate macro_rules_attribute; macro_rules! ToInteger {( #[repr($Int:ident)] $(#[$enum_meta:meta])* $pub:vis enum $Enum:ident { $( $Variant:ident $(= $value:expr)? ),* $(,)? } ) => ( impl ::core::convert::From<$Enum> for $Int { #[inline] fn from (x: $Enum) -> Self { x as _ } } )} #[macro_rules_derive(ToInteger)] // or `#[macro_rules_derive(ToInteger!)]` #[repr(u32)] enum Bool { False, True, } fn main () { assert_eq!(u32::from(Bool::False), 0); assert_eq!(u32::from(Bool::True), 1); // assert_eq!(u8::from(Bool::False), 0); // ^ error[E0277]: the trait bound `u8: std::convert::From` is not satisfied } ``` */ /// /// ## Difference with #\[[derive]\] /// /// #\[[macro_rules_derive]\] is specifically intended to be used /// with `macro_rules!`-based derives: /// /// - it won't accept classic derives; /// /// - thanks to that, the trailing `!` on the macro name is not mandatory. /// /// For #\[[derive]\], it's exactly the opposite. pub use ::macro_rules_attribute_proc_macro::macro_rules_derive; /// Convenience macro to define new derive aliases. /// /// The so-defined macros are intended to be used by /// #\[[macro_rules_derive]] or this crate's /// #\[[derive]]. /// /// ## Examples /// /** ```rust # fn main () {} #[macro_use] extern crate macro_rules_attribute; derive_alias! { #[derive(Copy!)] = #[derive(Clone, Copy)]; #[derive(Eq!)] = #[derive(PartialEq, Eq)]; #[derive(Ord!)] = #[derive(Eq!, PartialOrd, Ord)]; } #[derive(Debug, Copy!, Ord!)] struct Foo { // … } // Note: this defines `Copy!`, `Eq!` and `Ord!` as properly scoped // `crate`-local macros. mod example { use super::Copy; #[derive(Copy!, super::Eq!)] struct Bar; } ``` */ /// /** ```rust # fn main () {} #[macro_use] extern crate macro_rules_attribute; use ::core::{fmt::Debug, hash::Hash}; /// Trait alias pattern: `T : TheUsualSuspects ⇔ T : Debug + Copy + Ord + Hash`. trait TheUsualSuspects where // `⇒` direction Self : Debug + Copy + Ord + Hash, {} impl TheUsualSuspects for T where // `⇐` direction Self : Debug + Copy + Ord + Hash, {} derive_alias! { #[derive(TheUsualSuspects!)] = #[derive( Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, )]; } #[derive(TheUsualSuspects!)] struct KeyserSöze; const _: () = { fn compile_time_assert_impls () where T : TheUsualSuspects, {} let _ = compile_time_assert_impls::; }; ``` */ /// /// ### Caveat regarding derive helpers (inert-made attributes) /// ///
Click to see /// /// Some derive attributes (such as `{De,}Serialize`), can involve helper /// attributes (such as `#[serde]`). /// This yields /// inert /// derive-helper-attributes, /// which represent a _semantic_ aspect of the derive that /// **non-compiler-blessed macros such as this one cannot possibly know about**. /// /// This makes aliasing such derives problematic, **since the `derive` aliases /// won't be able to handle the helper attributes**. /// /** ```rust ,compile_fail # fn main () {} #[macro_use] extern crate macro_rules_attribute; derive_alias! { #[derive(Serde!)] = #[derive(::serde::Deserialize, ::serde::Serialize)]; } #[derive(Serde!)] #[serde(rename_all = "snake_case")] // Error, unknown `#[serde]` attribute struct Mejrs { swaginess: u8, } ``` */ /// /// The above, for instance, yields something along the lines of: /// /** ```rust # #[cfg(any())] macro_rules! ignore { error: cannot find attribute "serde" in this scope --> src/lib.rs:11:3 | 11 | #[serde(rename_all = "snake_case")] | ^^^^^ | = note: "serde" is in scope, but it is a crate, not an attribute # } ``` */ /// /// The only solution is to forgo the niceties of a `derive_alias!`, and define /// your own #\[[apply]\]-able `macro_rules_attribute` that aliases /// the `#[derive(…)]` attribute as a whole. [`attribute_alias!`] can come in /// handy in such situations: /// /** ```rust # fn main () {} #[macro_use] extern crate macro_rules_attribute; attribute_alias! { #[apply(derive_Serde)] = #[derive(::serde::Deserialize, ::serde::Serialize)]; } #[apply(derive_Serde)] #[serde(rename_all = "snake_case")] // OK struct Mejrs { swaginess: u8, } ``` */ /// /// ___ /// ///
#[macro_export] macro_rules! derive_alias {( $( #[derive($MacroName:ident !)] = #[derive($($derives:tt)*)]; )* ) => ( $crate::ඞ_with_dollar! {( $_:tt ) => ( $crate::ඞ::paste! { $( // To avoid ambiguities with what the re-export // refers to, let's use a hopefully unused name. // // Indeed, eponymous derive macros in scope such as those // from the prelude would otherwise cause trouble with the // re-export line. #[allow(nonstandard_style)] macro_rules! [< $MacroName __derive_macro >] {( $_($item:tt)* ) => ( $crate::ඞ_nested_derive! { #[derive($($derives)*)] $_($item)* } )} #[allow(unused_imports)] pub(in crate) use [< $MacroName __derive_macro >] as $MacroName; )* } )} )} /// Convenience macro to define new attribute aliases. /// /// The so-defined macros are intended to be used by #\[[apply]]. /// /// ## Examples /// /** ```rust # fn main () {} #[macro_use] extern crate macro_rules_attribute; attribute_alias! { #[apply(complex_cfg)] = #[cfg( any( test, doc, all( feature = "some very complex cfg", target_arch = "…", ), ) )]; #[apply(NOT_PART_OF_THE_PUBLIC_API!)] = /// Not part of the public API #[doc(hidden)] ; } #[apply(complex_cfg)] struct Foo { // … } #[apply(NOT_PART_OF_THE_PUBLIC_API!)] pub mod __macro_internals { // … } ``` */ /// #[macro_export] macro_rules! attribute_alias {( $( #[apply($name:ident $(!)?)] = $( #[$($attrs:tt)*] )+; )* ) => ( $( $crate::ඞ_with_dollar! {( $_:tt ) => ( // Let's not do the paste + module + re-export dance here since it // is less likely for an attribute name to collide with a prelude item. #[allow(nonstandard_style)] macro_rules! $name {( $_($item:tt)* ) => ( $( #[$($attrs)*] )+ $_($item)* )} #[allow(unused_imports)] pub(in crate) use $name; )} )* )} #[doc(hidden)] /** Not part of the public API*/ #[macro_export] macro_rules! ඞ_with_dollar {( $($rules:tt)* ) => ( macro_rules! __emit__ { $($rules)* } __emit__! { $ } )} /// Like #\[[macro_rules_derive]\], but for allowing to be /// used to shadow [the "built-in" `#[derive]` attribute][1] (on Rust ≥ 1.57.0). /// /// [1]: https://doc.rust-lang.org/stable/core/prelude/v1/macro.derive.html /// /// That is, it is made a bit more lenient to allow for things such as: /** ```rust #[macro_use] extern crate macro_rules_attribute; derive_alias! { #[derive(Eq!)] = #[derive(PartialEq, Eq)]; } #[derive(Debug, Eq!)] struct Foo; fn main () { assert_eq!(Foo, Foo); } ``` */ /// /// This is achieved thanks to **checking for the presence of a terminating `!` /// (or lack thereof)** to determine whether the given derive macro is a classic /// procedural macro one or a `macro_rules!` one. /// /// Also derives [`Custom`] to allow using `#[custom(...)]` and `#[derive_args(...)]` /// as derive helpers. pub use ::macro_rules_attribute_proc_macro::derive; /// No-op macro that is automatically derived with [`derive`] or [`macro_rules_derive`] /// to allow using the `#[custom(...)]` and `#[derive_args(...)]` attribute. /// /// See for more info. pub use ::macro_rules_attribute_proc_macro::Custom; attribute_alias! { #[apply(this_macro_is_private!)] = #[doc(hidden)] /// Not part of the public API #[macro_export] ; } mod nested_derive { //! Inlined mini-version of `::nested_derive`. #[crate::apply(this_macro_is_private!)] macro_rules! ඞ_nested_derive { ( #[derive( $($Derives:tt)* )] $($rest:tt)* ) => ( #[$crate::derive( $($Derives)* )] #[$crate::apply($crate::ඞ_dalek_EXTERMINATE!)] $($rest)* ); } // Ideally this would have been `dalek_☃_EXTERMINATE`, since the snowman // ressembles a Dalek more, which is a paramount aspect of this hidden macro // but for some reason Rust despises snowmen even though there are // ඞ-infected identifiers among (s)us… #[crate::apply(this_macro_is_private!)] macro_rules! ඞ_dalek_EXTERMINATE {( $it:item ) => ()} } #[doc(hidden)] /** Not part of the public API */ pub mod ඞ { pub use { ::paste::paste, }; } macro_rules_attribute-0.2.2/tests/custom_derive.rs000064400000000000000000000004561046102023000206100ustar 00000000000000#[macro_use] extern crate macro_rules_attribute; derive_alias! { #[derive(Nothing!)] = #[derive()]; } #[derive(Nothing!)] #[custom(hello)] struct Foo { #[derive_args("test")] x: i32, } #[macro_rules_derive(Nothing)] #[custom(hello)] struct Bar { #[derive_args("test")] x: i32, } macro_rules_attribute-0.2.2/tests/inert_derive_helpers.rs000064400000000000000000000003431046102023000221340ustar 00000000000000#[macro_use] extern crate macro_rules_attribute; use ::serde::Serialize; derive_alias! { #[derive(Nothing!)] = #[derive()]; } #[derive(Nothing!, Serialize)] #[serde(rename_all = "snake_case")] struct Foo { x: i32, }