derive_utils-0.14.2/.cargo_vcs_info.json0000644000000001360000000000100136160ustar { "git": { "sha1": "a8439005ad64b08f7371c9f0a6e99e5bc411e6e6" }, "path_in_vcs": "" }derive_utils-0.14.2/CHANGELOG.md000064400000000000000000000216541046102023000142270ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org). ## [Unreleased] ## [0.14.2] - 2024-08-23 - Disable `derive` feature of `syn` dependency. ## [0.14.1] - 2024-01-27 - Fix "overflow evaluating the requirement" error when the first variant and the other variant have the same type. - Fix a bug introduced in 0.14.0. ## [0.14.0] - 2024-01-27 **Note:** This release has been yanked due to a bug fixed in 0.14.1. - Allow `quote` variables in the trait definition of `quick_derive!` macro. This is considered as a breaking change because it will no longer allow a comma after the trait definition. - Change the second argument of `derive_trait` and `EnumImpl::from_trait` from `syn::Path` to `&syn::Path`. - Fix "overflow evaluating the requirement" error on recursive structures without type parameters. ([#47](https://github.com/taiki-e/derive_utils/issues/47)) ## [0.13.2] - 2023-07-27 - Fix diagnostic regression introduced in 0.13.0. ## [0.13.1] - 2023-06-29 - Fix build error from dependency when built with `-Z minimal-versions`. ## [0.13.0] - 2023-03-26 - Update `syn` dependency to 2. This increase the minimum supported Rust version from Rust 1.31 to Rust 1.56. ## [0.12.0] - 2022-01-10 - Remove support for `self: Pin<&(mut) Self>`. See [#41](https://github.com/taiki-e/derive_utils/pull/41) for more. ## [0.11.2] - 2021-01-05 - Exclude unneeded files from crates.io. ## [0.11.1] - 2020-12-29 - Documentation improvements. ## [0.11.0] - 2020-11-06 - `quick_derive!`, `derive_trait`, `EnumImpl::from_trait`, `EnumImpl::push_method`, and `EnumImpl::append_items_from_trait` are now panic if an unsupported trait definition passed, instead of return error. See [#35] for details. [#35]: https://github.com/taiki-e/derive_utils/pull/35 ## [0.10.0] - 2020-06-02 - `quick_derive!` macro now accepts both `proc_macro2::TokenStream` and `proc_macro::TokenStream` as input. - `quick_derive!` macro no longer supports trait path elision. - The parentheses that wrap the trait path passed to `quick_derive!` macro are no longer needed. For example: ```diff quick_derive! { input, // trait path - (std::iter::Iterator), + std::iter::Iterator, // trait definition trait Iterator { type Item; fn next(&mut self) -> Option; fn size_hint(&self) -> (usize, Option); } } ``` - The way of specifying super trait's associated types has been changed. ```diff quick_derive! { input, - // super trait's associated types - Item, - // trait path - (std::iter::ExactSizeIterator), + // trait path + std::iter::ExactSizeIterator, + // super trait's associated types + , // trait definition trait ExactSizeIterator: Iterator { fn len(&self) -> usize; } } ``` - Added `derive_trait` function. - Added `EnumImpl::{new, from_trait}` functions. - Added `EnumData::{field_types, variant_idents}` methods. - Removed `derive_trait!` macro in favor of `derive_trait` function. - Removed `EnumData::make_impl` and `EnumData::impl_with_capacity` in favor of `EnumImpl::new`. - Removed `EnumData::make_impl_trait` and `EnumData::impl_trait_with_capacity` in favor of `EnumImpl::from_trait`. - Removed `EnumImpl::push_generic_param_ident` in favor of `EnumImpl::push_generic_param(TypeParam::from(ident).into())`. - Removed `MaybeEnum` and `EnumElements` in favor of `syn::parse::()`. - Removed some hidden APIs. - Implemented `Deref`, `syn::parse::Parse`, and `quote::ToTokens` for `EnumData` - Implemented `From` for `syn::ItemEnum` ## [0.9.1] - 2019-09-15 - [Weakened requirements to a number of enum variants.](https://github.com/taiki-e/derive_utils/pull/15) ## [0.9.0] - 2019-08-14 - Updated `proc-macro2`, `syn`, and `quote` to 1.0. - Banned manual implementation of `MaybeEnum` for forward compatibility. - Added `vis: Visibility` field to `EnumElements`. - Hided some undocumented items from the public API. ## [0.8.0] - 2019-06-26 - Added `quote::ToTokens` bound to `MaybeEnum`. - Removed `EnumData::{from_item, from_derive}` in favor of `EnumData::new` - Improved error messages. ## [0.7.2] - 2019-05-30 - Improved error messages. ## [0.7.1] - 2019-05-21 - Improved support for arbitrary self type. - Improved error messages. ## [0.7.0] - 2019-03-13 - Transition to Rust 2018. With this change, the minimum required version will go up to Rust 1.31. - Improved error messages. - Removed `Error` and `Result` types. The current `derive_utils` uses [`syn::Error`](https://docs.rs/syn/0.15/syn/struct.Error.html) and [`syn::Result`](https://docs.rs/syn/0.15/syn/parse/type.Result.html) types. ## [0.6.3] - 2019-02-05 - Added `EnumData::new` method. - Updated minimum `syn` version to 0.15.22. - Removed dependency on `smallvec`. ## [0.6.2] - 2019-01-30 - Added `Error::to_compile_error` method. - Hided some undocumented items from the public API. ## [0.6.1] - 2019-01-26 - Improved support for `self: Pin<&Self>` and `self: Pin<&mut Self>`. - Updated minimum `smallvec` version to 0.6.8. ## [0.6.0] - 2019-01-09 - Removed `"std"` feature and `std_root` function. `derive_utils` can generate accurate code without `"std"` feature. - Removed deprecated `push_method_pin*` methods. Use `push_method` instead. - Documentation improvements. ## [0.5.4] - 2019-01-03 - Documentation improvements. ## [0.5.3] - 2018-12-27 - Improved macro implementations. The trailing comma is supported. - Improved error messages. ## [0.5.2] - 2018-12-27 - Hided some undocumented items from the public API. ## [0.5.1] - 2018-12-26 - Updated to stable Pin API. `Pin::get_mut_unchecked` renamed to `Pin::get_unchecked_mut` in [stabilization](https://github.com/rust-lang/rust/pull/56939). ## [0.5.0] - 2018-12-23 - Added `quick_derive` macro. - Removed `derive_trait_with_capacity` macro. ## [0.4.0] - 2018-12-22 - Added support for `self: Pin<&Self>` and `self: Pin<&mut Self>`. - Allow using the trait name as trait path. ## [0.3.0] - 2018-12-22 - Add `derive_trait` and `derive_trait_with_capacity` macros. With this change, the minimum required version will go up to Rust 1.30. ## [0.2.0] - 2018-12-20 - Support Rust 1.27. ## [0.1.1] - 2018-12-15 - Add `std::error::Error` impls for `derive_utils::Error`. ## [0.1.0] - 2018-12-15 **Note:** This release has been yanked. Initial release [Unreleased]: https://github.com/taiki-e/derive_utils/compare/v0.14.2...HEAD [0.14.2]: https://github.com/taiki-e/derive_utils/compare/v0.14.1...v0.14.2 [0.14.1]: https://github.com/taiki-e/derive_utils/compare/v0.14.0...v0.14.1 [0.14.0]: https://github.com/taiki-e/derive_utils/compare/v0.13.2...v0.14.0 [0.13.2]: https://github.com/taiki-e/derive_utils/compare/v0.13.1...v0.13.2 [0.13.1]: https://github.com/taiki-e/derive_utils/compare/v0.13.0...v0.13.1 [0.13.0]: https://github.com/taiki-e/derive_utils/compare/v0.12.0...v0.13.0 [0.12.0]: https://github.com/taiki-e/derive_utils/compare/v0.11.2...v0.12.0 [0.11.2]: https://github.com/taiki-e/derive_utils/compare/v0.11.1...v0.11.2 [0.11.1]: https://github.com/taiki-e/derive_utils/compare/v0.11.0...v0.11.1 [0.11.0]: https://github.com/taiki-e/derive_utils/compare/v0.10.0...v0.11.0 [0.10.0]: https://github.com/taiki-e/derive_utils/compare/v0.9.1...v0.10.0 [0.9.1]: https://github.com/taiki-e/derive_utils/compare/v0.9.0...v0.9.1 [0.9.0]: https://github.com/taiki-e/derive_utils/compare/v0.8.0...v0.9.0 [0.8.0]: https://github.com/taiki-e/derive_utils/compare/v0.7.2...v0.8.0 [0.7.2]: https://github.com/taiki-e/derive_utils/compare/v0.7.1...v0.7.2 [0.7.1]: https://github.com/taiki-e/derive_utils/compare/v0.7.0...v0.7.1 [0.7.0]: https://github.com/taiki-e/derive_utils/compare/v0.6.3...v0.7.0 [0.6.3]: https://github.com/taiki-e/derive_utils/compare/v0.6.2...v0.6.3 [0.6.2]: https://github.com/taiki-e/derive_utils/compare/v0.6.1...v0.6.2 [0.6.1]: https://github.com/taiki-e/derive_utils/compare/v0.6.0...v0.6.1 [0.6.0]: https://github.com/taiki-e/derive_utils/compare/v0.5.4...v0.6.0 [0.5.4]: https://github.com/taiki-e/derive_utils/compare/v0.5.3...v0.5.4 [0.5.3]: https://github.com/taiki-e/derive_utils/compare/v0.5.2...v0.5.3 [0.5.2]: https://github.com/taiki-e/derive_utils/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/taiki-e/derive_utils/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/taiki-e/derive_utils/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/taiki-e/derive_utils/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/taiki-e/derive_utils/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/taiki-e/derive_utils/compare/v0.1.1...v0.2.0 [0.1.1]: https://github.com/taiki-e/derive_utils/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/taiki-e/derive_utils/releases/tag/v0.1.0 derive_utils-0.14.2/Cargo.toml0000644000000071370000000000100116240ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "derive_utils" version = "0.14.2" build = false exclude = [ "/.*", "/tools", ] autobins = false autoexamples = false autotests = false autobenches = false description = """ A procedural macro helper for easily writing derive macros for enums. """ readme = "README.md" keywords = [ "enum", "macros", "derive", ] categories = [ "development-tools::procedural-macro-helpers", "rust-patterns", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/derive_utils" [package.metadata.cargo_check_external_types] allowed_external_types = [ "proc_macro2::*", "quote::*", "syn::*", ] [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "derive_utils" path = "src/lib.rs" doc-scrape-examples = false [[test]] name = "compiletest" path = "tests/compiletest.rs" [dependencies.proc-macro2] version = "1.0.60" [dependencies.quote] version = "1.0.25" [dependencies.syn] version = "2" features = [ "parsing", "printing", "clone-impls", "proc-macro", "full", ] default-features = false [dev-dependencies.rustversion] version = "1" [lints.clippy] all = "warn" as_ptr_cast_mut = "warn" as_underscore = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" pedantic = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" [lints.clippy.bool_assert_comparison] level = "allow" priority = 1 [lints.clippy.borrow_as_ptr] level = "allow" priority = 1 [lints.clippy.cast_lossless] level = "allow" priority = 1 [lints.clippy.declare_interior_mutable_const] level = "allow" priority = 1 [lints.clippy.doc_markdown] level = "allow" priority = 1 [lints.clippy.float_cmp] level = "allow" priority = 1 [lints.clippy.incompatible_msrv] level = "allow" priority = 1 [lints.clippy.lint_groups_priority] level = "allow" priority = 1 [lints.clippy.manual_assert] level = "allow" priority = 1 [lints.clippy.manual_range_contains] level = "allow" priority = 1 [lints.clippy.missing_errors_doc] level = "allow" priority = 1 [lints.clippy.module_name_repetitions] level = "allow" priority = 1 [lints.clippy.naive_bytecount] level = "allow" priority = 1 [lints.clippy.nonminimal_bool] level = "allow" priority = 1 [lints.clippy.range_plus_one] level = "allow" priority = 1 [lints.clippy.similar_names] level = "allow" priority = 1 [lints.clippy.single_match] level = "allow" priority = 1 [lints.clippy.single_match_else] level = "allow" priority = 1 [lints.clippy.struct_excessive_bools] level = "allow" priority = 1 [lints.clippy.struct_field_names] level = "allow" priority = 1 [lints.clippy.too_many_arguments] level = "allow" priority = 1 [lints.clippy.too_many_lines] level = "allow" priority = 1 [lints.clippy.type_complexity] level = "allow" priority = 1 [lints.clippy.unreadable_literal] level = "allow" priority = 1 [lints.rust] improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unreachable_pub = "warn" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = [] derive_utils-0.14.2/Cargo.toml.orig000064400000000000000000000101721046102023000152760ustar 00000000000000[package] name = "derive_utils" version = "0.14.2" #publish:version edition = "2021" rust-version = "1.56" license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/derive_utils" keywords = ["enum", "macros", "derive"] categories = ["development-tools::procedural-macro-helpers", "rust-patterns"] exclude = ["/.*", "/tools"] description = """ A procedural macro helper for easily writing derive macros for enums. """ [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [package.metadata.cargo_check_external_types] # The following are external types that are allowed to be exposed in our public API. allowed_external_types = [ "proc_macro2::*", "quote::*", "syn::*", ] [lib] doc-scrape-examples = false # Note: proc-macro2, quote, and syn are public dependencies. [dependencies] proc-macro2 = "1.0.60" quote = "1.0.25" syn = { version = "2", default-features = false, features = ["parsing", "printing", "clone-impls", "proc-macro", "full"] } [dev-dependencies] example_derive = { path = "examples/example_derive" } rustversion = "1" trybuild = { git = "https://github.com/taiki-e/trybuild.git", branch = "dev" } # adjust overwrite behavior [lints] workspace = true [workspace] resolver = "2" members = ["examples/example", "examples/example_derive"] # This table is shared by projects under github.com/taiki-e. # It is not intended for manual editing. [workspace.lints.rust] improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unexpected_cfgs = { level = "warn", check-cfg = [ ] } unreachable_pub = "warn" # unsafe_op_in_unsafe_fn = "warn" # Set at crate-level instead since https://github.com/rust-lang/rust/pull/100081 is not available on MSRV [workspace.lints.clippy] all = "warn" # Downgrade deny-by-default lints pedantic = "warn" as_ptr_cast_mut = "warn" as_underscore = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" # Suppress buggy or noisy clippy lints bool_assert_comparison = { level = "allow", priority = 1 } borrow_as_ptr = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/8286 cast_lossless = { level = "allow", priority = 1 } # https://godbolt.org/z/Pv6vbGG6E declare_interior_mutable_const = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7665 doc_markdown = { level = "allow", priority = 1 } float_cmp = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7725 incompatible_msrv = { level = "allow", priority = 1 } # buggy: doesn't consider cfg, https://github.com/rust-lang/rust-clippy/issues/12280, https://github.com/rust-lang/rust-clippy/issues/12257#issuecomment-2093667187 lint_groups_priority = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/12920 manual_assert = { level = "allow", priority = 1 } manual_range_contains = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/6455#issuecomment-1225966395 missing_errors_doc = { level = "allow", priority = 1 } module_name_repetitions = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+module_name_repetitions naive_bytecount = { level = "allow", priority = 1 } nonminimal_bool = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+nonminimal_bool range_plus_one = { level = "allow", priority = 1 } # buggy: https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+range_plus_one similar_names = { level = "allow", priority = 1 } single_match = { level = "allow", priority = 1 } single_match_else = { level = "allow", priority = 1 } struct_excessive_bools = { level = "allow", priority = 1 } struct_field_names = { level = "allow", priority = 1 } too_many_arguments = { level = "allow", priority = 1 } too_many_lines = { level = "allow", priority = 1 } type_complexity = { level = "allow", priority = 1 } unreadable_literal = { level = "allow", priority = 1 } derive_utils-0.14.2/LICENSE-APACHE000064400000000000000000000236761046102023000143500ustar 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 derive_utils-0.14.2/LICENSE-MIT000064400000000000000000000017771046102023000140560ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. derive_utils-0.14.2/README.md000064400000000000000000000076051046102023000136750ustar 00000000000000# derive_utils [![crates.io](https://img.shields.io/crates/v/derive_utils?style=flat-square&logo=rust)](https://crates.io/crates/derive_utils) [![docs.rs](https://img.shields.io/badge/docs.rs-derive__utils-blue?style=flat-square&logo=docs.rs)](https://docs.rs/derive_utils) [![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue?style=flat-square)](#license) [![msrv](https://img.shields.io/badge/msrv-1.56-blue?style=flat-square&logo=rust)](https://www.rust-lang.org) [![github actions](https://img.shields.io/github/actions/workflow/status/taiki-e/derive_utils/ci.yml?branch=main&style=flat-square&logo=github)](https://github.com/taiki-e/derive_utils/actions) A procedural macro helper for easily writing [derives macros][proc-macro-derive] for enums. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] derive_utils = "0.14" ``` ## Examples [`quick_derive!`] macro make easy to write [`proc_macro_derive`][proc-macro-derive] like deriving trait to enum so long as all variants are implemented that trait. ```rust use derive_utils::quick_derive; use proc_macro::TokenStream; #[proc_macro_derive(Iterator)] pub fn derive_iterator(input: TokenStream) -> TokenStream { quick_derive! { input, // trait path std::iter::Iterator, // trait definition trait Iterator { type Item; fn next(&mut self) -> Option; fn size_hint(&self) -> (usize, Option); } } } #[proc_macro_derive(ExactSizeIterator)] pub fn derive_exact_size_iterator(input: TokenStream) -> TokenStream { quick_derive! { input, // trait path std::iter::ExactSizeIterator, // super trait's associated types , // trait definition trait ExactSizeIterator: Iterator { fn len(&self) -> usize; } } } ``` ### Generated code When deriving for enum like the following: ```rust #[derive(Iterator, ExactSizeIterator, Future)] enum Enum { A(A), B(B), } ``` Code like this will be generated: ```rust enum Enum { A(A), B(B), } impl std::iter::Iterator for Enum where A: std::iter::Iterator, B: std::iter::Iterator::Item>, { type Item = ::Item; fn next(&mut self) -> Option { match self { Enum::A(x) => x.next(), Enum::B(x) => x.next(), } } fn size_hint(&self) -> (usize, Option) { match self { Enum::A(x) => x.size_hint(), Enum::B(x) => x.size_hint(), } } } impl std::iter::ExactSizeIterator for Enum where A: std::iter::ExactSizeIterator, B: std::iter::ExactSizeIterator::Item>, { fn len(&self) -> usize { match self { Enum::A(x) => x.len(), Enum::B(x) => x.len(), } } } ``` ## Related Projects - [auto_enums]: A library for to allow multiple return types by automatically generated enum. - [io-enum]: \#\[derive(Read, Write, Seek, BufRead)\] for enums. - [iter-enum]: \#\[derive(Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Extend)\] for enums. [auto_enums]: https://github.com/taiki-e/auto_enums [io-enum]: https://github.com/taiki-e/io-enum [iter-enum]: https://github.com/taiki-e/iter-enum [proc-macro-derive]: https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros [`quick_derive!`]: https://docs.rs/derive_utils/latest/derive_utils/macro.quick_derive.html ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT license](LICENSE-MIT) at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. derive_utils-0.14.2/src/ast.rs000064400000000000000000000053761046102023000143450ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use core::ops; use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parse::{Parse, ParseStream}, Fields, Ident, ItemEnum, Result, Type, }; /// A structure to make trait implementation to enums more efficient. pub struct EnumData { repr: ItemEnum, field_types: Vec, } impl EnumData { /// Returns an iterator over field types. /// /// ```text /// enum Enum { /// VariantA(TypeA), /// ^^^^^ /// VariantB(TypeB), /// ^^^^^ /// } /// ``` pub fn field_types(&self) -> impl ExactSizeIterator + Clone { self.field_types.iter() } /// Returns an iterator over variant names. /// /// ```text /// enum Enum { /// VariantA(TypeA), /// ^^^^^^^^ /// VariantB(TypeB), /// ^^^^^^^^ /// } /// ``` pub fn variant_idents(&self) -> impl ExactSizeIterator + Clone { self.variants.iter().map(|v| &v.ident) } } impl ops::Deref for EnumData { type Target = ItemEnum; fn deref(&self) -> &Self::Target { &self.repr } } impl From for ItemEnum { fn from(other: EnumData) -> Self { other.repr } } impl Parse for EnumData { fn parse(input: ParseStream<'_>) -> Result { let item: ItemEnum = input.parse()?; if item.variants.is_empty() { bail!(item, "may not be used on enums without variants"); } let field_types = item.variants.iter().try_fold( Vec::with_capacity(item.variants.len()), |mut field_types, v| { if let Some((_, e)) = &v.discriminant { bail!(e, "may not be used on enums with discriminants"); } if v.fields.is_empty() { bail!(v, "may not be used on enums with variants with zero fields"); } else if v.fields.len() != 1 { bail!(v, "may not be used on enums with variants with multiple fields"); } match &v.fields { Fields::Unnamed(f) => { field_types.push(f.unnamed.iter().next().unwrap().ty.clone()); Ok(field_types) } Fields::Named(_) => { bail!(v, "may not be used on enums with variants with named fields"); } Fields::Unit => unreachable!(), } }, )?; Ok(Self { repr: item, field_types }) } } impl ToTokens for EnumData { fn to_tokens(&self, tokens: &mut TokenStream) { self.repr.to_tokens(tokens); } } derive_utils-0.14.2/src/error.rs000064400000000000000000000006161046102023000146770ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT macro_rules! format_err { ($span:expr, $msg:expr $(,)?) => { syn::Error::new_spanned(&$span as &dyn quote::ToTokens, &$msg as &dyn core::fmt::Display) }; ($span:expr, $($tt:tt)*) => { format_err!($span, format!($($tt)*)) }; } macro_rules! bail { ($($tt:tt)*) => { return Err(format_err!($($tt)*)) }; } derive_utils-0.14.2/src/lib.rs000064400000000000000000000137571046102023000143260ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT /*! A procedural macro helper for easily writing [derives macros][proc-macro-derive] for enums. ## Examples [`quick_derive!`] macro make easy to write [`proc_macro_derive`][proc-macro-derive] like deriving trait to enum so long as all variants are implemented that trait. ```rust # extern crate proc_macro; use derive_utils::quick_derive; use proc_macro::TokenStream; # #[cfg(any())] #[proc_macro_derive(Iterator)] # pub fn _derive_iterator(_: TokenStream) -> TokenStream { unimplemented!() } pub fn derive_iterator(input: TokenStream) -> TokenStream { quick_derive! { input, // trait path std::iter::Iterator, // trait definition trait Iterator { type Item; fn next(&mut self) -> Option; fn size_hint(&self) -> (usize, Option); } } } # #[cfg(any())] #[proc_macro_derive(ExactSizeIterator)] # pub fn _derive_exact_size_iterator(_: TokenStream) -> TokenStream { unimplemented!() } pub fn derive_exact_size_iterator(input: TokenStream) -> TokenStream { quick_derive! { input, // trait path std::iter::ExactSizeIterator, // super trait's associated types , // trait definition trait ExactSizeIterator: Iterator { fn len(&self) -> usize; } } } ``` ### Generated code When deriving for enum like the following: ```rust # #[cfg(any())] #[derive(Iterator, ExactSizeIterator, Future)] # struct _Enum(A); enum Enum { A(A), B(B), } ``` Code like this will be generated: ```rust enum Enum { A(A), B(B), } impl std::iter::Iterator for Enum where A: std::iter::Iterator, B: std::iter::Iterator::Item>, { type Item = ::Item; fn next(&mut self) -> Option { match self { Enum::A(x) => x.next(), Enum::B(x) => x.next(), } } fn size_hint(&self) -> (usize, Option) { match self { Enum::A(x) => x.size_hint(), Enum::B(x) => x.size_hint(), } } } impl std::iter::ExactSizeIterator for Enum where A: std::iter::ExactSizeIterator, B: std::iter::ExactSizeIterator::Item>, { fn len(&self) -> usize { match self { Enum::A(x) => x.len(), Enum::B(x) => x.len(), } } } ``` ## Related Projects - [auto_enums]: A library for to allow multiple return types by automatically generated enum. - [io-enum]: \#\[derive(Read, Write, Seek, BufRead)\] for enums. - [iter-enum]: \#\[derive(Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, Extend)\] for enums. [auto_enums]: https://github.com/taiki-e/auto_enums [io-enum]: https://github.com/taiki-e/io-enum [iter-enum]: https://github.com/taiki-e/iter-enum [proc-macro-derive]: https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros */ #![doc(test( no_crate_inject, attr( deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code, unused_variables) ) ))] #![forbid(unsafe_code)] #![warn( // Lints that may help when writing public library. // missing_debug_implementations, // missing_docs, clippy::alloc_instead_of_core, clippy::exhaustive_enums, clippy::exhaustive_structs, clippy::impl_trait_in_params, // clippy::missing_inline_in_public_items, // clippy::std_instead_of_alloc, clippy::std_instead_of_core, )] #![allow(clippy::must_use_candidate)] #[macro_use] mod error; mod ast; mod parse; pub use crate::{ ast::EnumData, parse::{derive_trait, EnumImpl}, }; /// A macro for making easy to write `proc_macro_derive` like deriving trait to /// enum so long as all variants are implemented that trait. /// /// See crate level documentation for details. #[macro_export] macro_rules! quick_derive { ($input:expr, $trait_path:expr, <$super:ident>, $($trait_def:tt)*) => { $crate::__private::parse_input($input, |data| { $crate::derive_trait( &data, &$crate::__private::parse_quote!($trait_path), $crate::__private::Some( $crate::__private::format_ident!($crate::__private::stringify!($super)) ), $crate::__private::parse_quote!($($trait_def)*), ) }) .into() }; ($input:expr, $trait_path:expr, <$($super:ident),+ $(,)?>, $($trait_def:tt)*) => { $crate::__private::parse_input($input, |data| { $crate::derive_trait( &data, &$crate::__private::parse_quote!($trait_path), $crate::__private::vec![ $( $crate::__private::format_ident!($crate::__private::stringify!($super)) ),+ ], $crate::__private::parse_quote!($($trait_def)*), ) }) .into() }; ($input:expr, $trait_path:expr, $($trait_def:tt)*) => { $crate::__private::parse_input($input, |data| { $crate::derive_trait( &data, &$crate::__private::parse_quote!($trait_path), $crate::__private::None, $crate::__private::parse_quote!($($trait_def)*), ) }) .into() }; } // Not public API. #[doc(hidden)] pub mod __private { #[doc(hidden)] pub use core::{ option::Option::{None, Some}, stringify, }; #[doc(hidden)] pub use std::vec; use proc_macro2::TokenStream; #[doc(hidden)] pub use quote::{format_ident, quote}; use syn::Error; #[doc(hidden)] pub use syn::{parse2, parse_quote, ItemTrait, Path}; use crate::EnumData; #[doc(hidden)] pub fn parse_input, F: Fn(EnumData) -> TokenStream>( input: T, f: F, ) -> TokenStream { parse2::(input.into()).map_or_else(Error::into_compile_error, f) } } derive_utils-0.14.2/src/parse.rs000064400000000000000000000365661046102023000146750ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use core::mem; use std::borrow::Cow; use proc_macro2::{TokenStream, TokenTree}; use quote::{quote, ToTokens}; use syn::{ parse_quote, token, Block, FnArg, GenericParam, Generics, Ident, ImplItem, ImplItemFn, ItemImpl, ItemTrait, Path, Signature, Stmt, Token, TraitItem, TraitItemFn, TraitItemType, Type, TypeParamBound, TypePath, Visibility, WherePredicate, }; use crate::ast::EnumData; /// A function for creating `proc_macro_derive` like deriving trait to enum so /// long as all variants are implemented that trait. /// /// # Examples /// /// ``` /// # extern crate proc_macro; /// use derive_utils::derive_trait; /// use proc_macro::TokenStream; /// use quote::format_ident; /// use syn::{parse_macro_input, parse_quote}; /// /// # #[cfg(any())] /// #[proc_macro_derive(Iterator)] /// # pub fn _derive_iterator(_: TokenStream) -> TokenStream { unimplemented!() } /// pub fn derive_iterator(input: TokenStream) -> TokenStream { /// derive_trait( /// &parse_macro_input!(input), /// // trait path /// &parse_quote!(std::iter::Iterator), /// // super trait's associated types /// None, /// // trait definition /// parse_quote! { /// trait Iterator { /// type Item; /// fn next(&mut self) -> Option; /// fn size_hint(&self) -> (usize, Option); /// } /// }, /// ) /// .into() /// } /// /// # #[cfg(any())] /// #[proc_macro_derive(ExactSizeIterator)] /// # pub fn _derive_exact_size_iterator(_: TokenStream) -> TokenStream { unimplemented!() } /// pub fn derive_exact_size_iterator(input: TokenStream) -> TokenStream { /// derive_trait( /// &parse_macro_input!(input), /// // trait path /// &parse_quote!(std::iter::ExactSizeIterator), /// // super trait's associated types /// Some(format_ident!("Item")), /// // trait definition /// parse_quote! { /// trait ExactSizeIterator: Iterator { /// fn len(&self) -> usize; /// } /// }, /// ) /// .into() /// } /// ``` pub fn derive_trait( data: &EnumData, trait_path: &Path, supertraits_types: I, trait_def: ItemTrait, ) -> TokenStream where I: IntoIterator, I::IntoIter: ExactSizeIterator, { EnumImpl::from_trait(data, trait_path, supertraits_types, trait_def).build() } /// A builder for implementing a trait for enums. pub struct EnumImpl<'a> { data: &'a EnumData, defaultness: bool, unsafety: bool, generics: Generics, trait_: Option, self_ty: Box, items: Vec, } impl<'a> EnumImpl<'a> { /// Creates a new `EnumImpl`. pub fn new(data: &'a EnumData) -> Self { let ident = &data.ident; let ty_generics = data.generics.split_for_impl().1; Self { data, defaultness: false, unsafety: false, generics: data.generics.clone(), trait_: None, self_ty: Box::new(parse_quote!(#ident #ty_generics)), items: vec![], } } /// Creates a new `EnumImpl` from a trait definition. /// /// The following items are ignored: /// - Generic associated types (GAT) ([`TraitItem::Type`] that has generics) /// - [`TraitItem::Const`] /// - [`TraitItem::Macro`] /// - [`TraitItem::Verbatim`] /// /// # Panics /// /// Panics if a trait method has a body, no receiver, or a receiver other /// than the following: /// /// - `&self` /// - `&mut self` /// - `self` pub fn from_trait( data: &'a EnumData, trait_path: &Path, supertraits_types: I, mut trait_def: ItemTrait, ) -> Self where I: IntoIterator, I::IntoIter: ExactSizeIterator, { let mut generics = data.generics.clone(); let trait_ = { if trait_def.generics.params.is_empty() { trait_path.clone() } else { let ty_generics = trait_def.generics.split_for_impl().1; parse_quote!(#trait_path #ty_generics) } }; let fst = data.field_types().next().unwrap(); let mut types: Vec<_> = trait_def .items .iter() .filter_map(|item| match item { TraitItem::Type(ty) => Some((false, Cow::Borrowed(&ty.ident))), _ => None, }) .collect(); let supertraits_types = supertraits_types.into_iter(); if supertraits_types.len() > 0 { if let Some(TypeParamBound::Trait(_)) = trait_def.supertraits.iter().next() { types.extend(supertraits_types.map(|ident| (true, Cow::Owned(ident)))); } } // https://github.com/taiki-e/derive_utils/issues/47 let type_params = generics.type_params().map(|p| p.ident.to_string()).collect::>(); let has_method = trait_def.items.iter().any(|i| matches!(i, TraitItem::Fn(..))); if !has_method || !type_params.is_empty() { struct HasTypeParam<'a>(&'a [String]); impl HasTypeParam<'_> { fn check_ident(&self, ident: &Ident) -> bool { let ident = ident.to_string(); self.0.contains(&ident) } fn visit_type(&self, ty: &Type) -> bool { if let Type::Path(node) = ty { if node.qself.is_none() { if let Some(ident) = node.path.get_ident() { return self.check_ident(ident); } } } self.visit_token_stream(ty.to_token_stream()) } fn visit_token_stream(&self, tokens: TokenStream) -> bool { for tt in tokens { match tt { TokenTree::Ident(ident) => { if self.check_ident(&ident) { return true; } } TokenTree::Group(group) => { let content = group.stream(); if self.visit_token_stream(content) { return true; } } _ => {} } } false } } let visitor = HasTypeParam(&type_params); let where_clause = &mut generics.make_where_clause().predicates; if !has_method || visitor.visit_type(fst) { where_clause.push(parse_quote!(#fst: #trait_)); } if data.field_types().len() > 1 { let fst_tokens = fst.to_token_stream().to_string(); where_clause.extend(data.field_types().skip(1).filter_map( |variant| -> Option { if has_method && !visitor.visit_type(variant) { return None; } if variant.to_token_stream().to_string() == fst_tokens { return None; } if types.is_empty() { return Some(parse_quote!(#variant: #trait_)); } let types = types.iter().map(|(supertraits, ident)| { match trait_def.supertraits.iter().next() { Some(TypeParamBound::Trait(trait_)) if *supertraits => { quote!(#ident = <#fst as #trait_>::#ident) } _ => quote!(#ident = <#fst as #trait_>::#ident), } }); if trait_def.generics.params.is_empty() { Some(parse_quote!(#variant: #trait_path<#(#types),*>)) } else { let generics = trait_def.generics.params.iter().map(|param| match param { GenericParam::Lifetime(def) => def.lifetime.to_token_stream(), GenericParam::Type(param) => param.ident.to_token_stream(), GenericParam::Const(param) => param.ident.to_token_stream(), }); Some(parse_quote!(#variant: #trait_path<#(#generics),*, #(#types),*>)) } }, )); } } if !trait_def.generics.params.is_empty() { generics.params.extend(mem::take(&mut trait_def.generics.params)); } if let Some(old) = trait_def.generics.where_clause.as_mut() { if !old.predicates.is_empty() { generics.make_where_clause().predicates.extend(mem::take(&mut old.predicates)); } } let ident = &data.ident; let ty_generics = data.generics.split_for_impl().1; let mut impls = Self { data, defaultness: false, unsafety: trait_def.unsafety.is_some(), generics, trait_: Some(trait_), self_ty: Box::new(parse_quote!(#ident #ty_generics)), items: Vec::with_capacity(trait_def.items.len()), }; impls.append_items_from_trait(trait_def); impls } pub fn set_trait(&mut self, path: Path) { self.trait_ = Some(path); } /// Appends a generic type parameter to the back of generics. pub fn push_generic_param(&mut self, param: GenericParam) { self.generics.params.push(param); } /// Appends a predicate to the back of `where`-clause. pub fn push_where_predicate(&mut self, predicate: WherePredicate) { self.generics.make_where_clause().predicates.push(predicate); } /// Appends an item to impl items. pub fn push_item(&mut self, item: ImplItem) { self.items.push(item); } /// Appends a method to impl items. /// /// # Panics /// /// Panics if a trait method has a body, no receiver, or a receiver other /// than the following: /// /// - `&self` /// - `&mut self` /// - `self` pub fn push_method(&mut self, item: TraitItemFn) { assert!(item.default.is_none(), "method `{}` has a body", item.sig.ident); let self_ty = ReceiverKind::new(&item.sig); let mut args = Vec::with_capacity(item.sig.inputs.len()); item.sig.inputs.iter().skip(1).for_each(|arg| match arg { FnArg::Typed(arg) => args.push(&arg.pat), FnArg::Receiver(_) => panic!( "method `{}` has a receiver in a position other than the first argument", item.sig.ident ), }); let method = &item.sig.ident; let ident = &self.data.ident; let method = match self_ty { ReceiverKind::Normal => match &self.trait_ { None => { let arms = self.data.variant_idents().map(|v| { quote! { #ident::#v(x) => x.#method(#(#args),*), } }); parse_quote!(match self { #(#arms)* }) } Some(trait_) => { let arms = self.data.variant_idents().zip(self.data.field_types()).map(|(v, ty)| { quote! { #ident::#v(x) => <#ty as #trait_>::#method(x #(,#args)*), } }); parse_quote!(match self { #(#arms)* }) } }, }; self.push_item(ImplItem::Fn(ImplItemFn { attrs: item.attrs, vis: Visibility::Inherited, defaultness: None, sig: item.sig, block: Block { brace_token: token::Brace::default(), stmts: vec![Stmt::Expr(method, None)], }, })); } /// Appends items from a trait definition to impl items. /// /// # Panics /// /// Panics if a trait method has a body, no receiver, or a receiver other /// than the following: /// /// - `&self` /// - `&mut self` /// - `self` pub fn append_items_from_trait(&mut self, trait_def: ItemTrait) { let fst = self.data.field_types().next(); trait_def.items.into_iter().for_each(|item| match item { // The TraitItemType::generics field (Generic associated types (GAT)) are not supported TraitItem::Type(TraitItemType { ident, .. }) => { let trait_ = &self.trait_; let ty = parse_quote!(type #ident = <#fst as #trait_>::#ident;); self.push_item(ImplItem::Type(ty)); } TraitItem::Fn(method) => self.push_method(method), _ => {} }); } pub fn build(self) -> TokenStream { self.build_impl().to_token_stream() } pub fn build_impl(self) -> ItemImpl { ItemImpl { attrs: vec![], defaultness: if self.defaultness { Some(::default()) } else { None }, unsafety: if self.unsafety { Some(::default()) } else { None }, impl_token: token::Impl::default(), generics: self.generics, trait_: self.trait_.map(|trait_| (None, trait_, ::default())), self_ty: self.self_ty, brace_token: token::Brace::default(), items: self.items, } } } enum ReceiverKind { /// `&(mut) self`, `(mut) self`, `(mut) self: &(mut) Self`, or `(mut) self: Self` Normal, } impl ReceiverKind { fn new(sig: &Signature) -> Self { fn get_ty_path(ty: &Type) -> Option<&Path> { if let Type::Path(TypePath { qself: None, path }) = ty { Some(path) } else { None } } match sig.receiver() { None => panic!("method `{}` has no receiver", sig.ident), Some(receiver) => { if receiver.colon_token.is_none() { return ReceiverKind::Normal; } match &*receiver.ty { Type::Path(TypePath { qself: None, path }) => { // (mut) self: Self if path.is_ident("Self") { return ReceiverKind::Normal; } } Type::Reference(ty) => { // (mut) self: &(mut) Self if get_ty_path(&ty.elem).map_or(false, |path| path.is_ident("Self")) { return ReceiverKind::Normal; } } _ => {} } panic!( "method `{}` has unsupported receiver type: {}", sig.ident, receiver.ty.to_token_stream() ); } } } } derive_utils-0.14.2/tests/compiletest.rs000064400000000000000000000003701046102023000164460ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT #![cfg(not(miri))] #[rustversion::attr(not(nightly), ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/**/*.rs"); t.pass("tests/run-pass/**/*.rs"); } derive_utils-0.14.2/tests/ui/variant.rs000064400000000000000000000014571046102023000162060ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use example_derive::Iterator; #[derive(Iterator)] enum EnumWZV {} //~ ERROR may not be used on enums without variants #[derive(Iterator)] enum EnumWD { A = 2, //~ ERROR may not be used on enums with discriminants B, } #[derive(Iterator)] enum EnumWZF1 { A, //~ ERROR may not be used on enums with variants with zero fields B(B), } #[derive(Iterator)] enum EnumWZF2 { A(), //~ ERROR may not be used on enums with variants with zero fields B(B), } #[derive(Iterator)] enum EnumWMF { A(A), B(A, B), //~ ERROR may not be used on enums with variants with multiple fields } #[derive(Iterator)] enum EnumWNF { A { x: A }, //~ ERROR may not be used on enums with variants with named fields B(B), } fn main() {} derive_utils-0.14.2/tests/ui/variant.stderr000064400000000000000000000021731046102023000170610ustar 00000000000000error: may not be used on enums without variants --> tests/ui/variant.rs:6:1 | 6 | enum EnumWZV {} //~ ERROR may not be used on enums without variants | ^^^^^^^^^^^^^^^ error: may not be used on enums with discriminants --> tests/ui/variant.rs:10:9 | 10 | A = 2, //~ ERROR may not be used on enums with discriminants | ^ error: may not be used on enums with variants with zero fields --> tests/ui/variant.rs:16:5 | 16 | A, //~ ERROR may not be used on enums with variants with zero fields | ^ error: may not be used on enums with variants with zero fields --> tests/ui/variant.rs:22:5 | 22 | A(), //~ ERROR may not be used on enums with variants with zero fields | ^^^ error: may not be used on enums with variants with multiple fields --> tests/ui/variant.rs:29:5 | 29 | B(A, B), //~ ERROR may not be used on enums with variants with multiple fields | ^^^^^^^ error: may not be used on enums with variants with named fields --> tests/ui/variant.rs:34:5 | 34 | A { x: A }, //~ ERROR may not be used on enums with variants with named fields | ^^^^^^^^^^