├── .github └── workflows │ ├── gh-pages.yml │ ├── release.yml │ └── test-suite.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── book ├── .gitignore ├── book.toml └── src │ ├── SUMMARY.md │ ├── codegen.md │ ├── codegen │ ├── enum.md │ ├── map-macros.md │ ├── meta-variants.md │ ├── ref-and-refmut.md │ └── variant-structs.md │ ├── config.md │ ├── config │ ├── field.md │ └── struct.md │ ├── intro.md │ └── setup.md ├── examples ├── customer.rs ├── nested.rs └── request.rs ├── src ├── attributes.rs ├── from.rs ├── lib.rs ├── macros.rs ├── naming.rs └── utils.rs └── tests ├── basic.rs ├── flatten.rs ├── from.rs ├── map_macro.rs ├── meta_variant.rs ├── ref.rs ├── ref_mut.rs └── specific_variant_attributes.rs /.github/workflows/gh-pages.yml: -------------------------------------------------------------------------------- 1 | name: gh-pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | deploy: 11 | runs-on: ubuntu-latest 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.ref }} 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Install mdBook 17 | uses: peaceiris/actions-mdbook@v1 18 | with: 19 | mdbook-version: 'latest' 20 | - name: Build book and RustDoc 21 | run: make docs 22 | - name: Deploy 23 | uses: peaceiris/actions-gh-pages@v3 24 | if: ${{ github.ref == 'refs/heads/main' }} 25 | with: 26 | github_token: ${{ secrets.GITHUB_TOKEN }} 27 | publish_dir: ./docs 28 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | on: 3 | push: 4 | tags: 5 | - v* 6 | jobs: 7 | check-version: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - name: Check version 12 | run: | 13 | TAG_VERSION=$(echo ${GITHUB_REF#refs/tags/v}) 14 | CRATE_VERSION=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].version') 15 | test "$TAG_VERSION" = "$CRATE_VERSION" 16 | publish: 17 | runs-on: ubuntu-latest 18 | needs: check-version 19 | env: 20 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 21 | steps: 22 | - uses: actions/checkout@v3 23 | - name: Publish 24 | run: cargo publish 25 | -------------------------------------------------------------------------------- /.github/workflows/test-suite.yml: -------------------------------------------------------------------------------- 1 | name: test-suite 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - 'pr/*' 8 | pull_request: 9 | env: 10 | # Deny warnings in CI 11 | RUSTFLAGS: "-D warnings" 12 | jobs: 13 | cargo-fmt: 14 | name: cargo-fmt 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v1 18 | - name: Get latest version of stable Rust 19 | run: rustup update stable 20 | - name: Check formatting with cargo fmt 21 | run: cargo fmt --all -- --check 22 | clippy: 23 | name: clippy 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: actions/checkout@v1 27 | - name: Get latest version of stable Rust 28 | run: rustup update stable 29 | - name: Check formatting with cargo fmt 30 | run: cargo clippy --tests --release 31 | test: 32 | name: test 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v1 36 | - name: Get latest version of stable Rust 37 | run: rustup update stable 38 | - name: Run tests 39 | run: cargo test --release 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target/ 3 | docs/ 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "superstruct" 3 | version = "0.9.0" 4 | edition = "2021" 5 | description = "Versioned data types with minimal boilerplate" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/sigp/superstruct" 8 | documentation = "https://sigp.github.io/superstruct/" 9 | keywords = ["schema", "subtype", "compatibility", "macro"] 10 | categories = ["rust-patterns"] 11 | 12 | [lib] 13 | name = "superstruct" 14 | proc-macro = true 15 | 16 | [dependencies] 17 | darling = "0.20.10" 18 | itertools = "0.13.0" 19 | proc-macro2 = "1.0.89" 20 | quote = "1.0.37" 21 | syn = "2.0.86" 22 | smallvec = "1.13.2" 23 | 24 | [dev-dependencies] 25 | serde = { version = "1.0.130", features = ["derive"] } 26 | serde_json = "1.0.72" 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 to present, Sigma Prime and SuperStruct contributors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | docs: 2 | rm -rf $@ 3 | cargo doc --examples 4 | mdbook build book 5 | mkdir -p $@ 6 | cp -r book/book/* $@ 7 | cp -r target/doc $@/rustdoc 8 | 9 | clean: 10 | rm -rf docs 11 | 12 | .PHONY: docs clean 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SuperStruct 2 | =========== 3 | 4 | ![test status](https://github.com/sigp/superstruct/actions/workflows/test-suite.yml/badge.svg) 5 | ![crates.io](https://img.shields.io/crates/v/superstruct.svg) 6 | 7 | SuperStruct is a library for working with a family of related struct _variants_, where each variant shares some common fields, and adds in unique fields of its own. 8 | 9 | For more information please see the [SuperStruct Guide](https://sigp.github.io/superstruct/). 10 | 11 | ## Project Showcase 12 | 13 | SuperStruct is used in the following projects: 14 | 15 | * [`sigp/lighthouse`](https://github.com/sigp/lighthouse): Ethereum consensus client 16 | 17 | ## License 18 | 19 | Apache 2.0 20 | -------------------------------------------------------------------------------- /book/.gitignore: -------------------------------------------------------------------------------- 1 | book 2 | -------------------------------------------------------------------------------- /book/book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Sigma Prime"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "SuperStruct Guide" 7 | -------------------------------------------------------------------------------- /book/src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | - [Introduction](./intro.md) 4 | - [Setup](./setup.md) 5 | - [Code generation](./codegen.md) 6 | - [Variant structs](./codegen/variant-structs.md) 7 | - [Top-level enum](./codegen/enum.md) 8 | - [`Ref` and `RefMut`](./codegen/ref-and-refmut.md) 9 | - [Mapping macros](./codegen/map-macros.md) 10 | - [Configuration](./config.md) 11 | - [Struct attributes](./config/struct.md) 12 | - [Field attributes](./config/field.md) 13 | -------------------------------------------------------------------------------- /book/src/codegen.md: -------------------------------------------------------------------------------- 1 | # Code generation 2 | 3 | SuperStruct generates several types, methods and trait implementations. 4 | 5 | You should visit each of the sub-pages in order to understand how the generated code fits together: 6 | 7 | 1. [Variant structs](./codegen/variant-structs.md). 8 | 2. [Top-level enum](./codegen/enum.md). 9 | 3. [`Ref` and `RefMut`](./codegen/ref-and-refmut.md). 10 | 4. [Mapping macros](./codegen/map-macros.md). 11 | 12 | ## Example 13 | 14 | For a full, up-to-date example of the code generated, please see the [RustDoc output for 15 | the `Request` example](./rustdoc/request). 16 | -------------------------------------------------------------------------------- /book/src/codegen/enum.md: -------------------------------------------------------------------------------- 1 | # Top-level enum 2 | 3 | SuperStruct generates an enum that combines all of the generated variant structs. 4 | 5 | Consider the the `MyStruct` example from the previous page: 6 | 7 | ```rust,no_run,no_playground 8 | #[superstruct(variants(Foo, Bar))] 9 | struct MyStruct { 10 | name: String, 11 | #[superstruct(only(Foo))] 12 | location: u16, 13 | } 14 | ``` 15 | 16 | The generated enum is: 17 | 18 | ```rust,no_run,no_playground 19 | enum MyStruct { 20 | Foo(MyStructFoo), 21 | Bar(MyStructBar), 22 | } 23 | ``` 24 | 25 | The enum has one variant per variant in `superstruct(variants(..))`, and each 26 | variant contains its generated variant struct. It is named `{BaseName}`. 27 | 28 | Generation of the top-level enum can be disabled using the `no_enum` attribute. For more information 29 | see the [Struct attributes](../config/struct.md). 30 | 31 | ## Getters and setters 32 | 33 | The top-level enum has getters and setters for each of the variant fields. They are named: 34 | 35 | * `{field_name}()` for getters. 36 | * `{field_name}_mut()` for setters. 37 | 38 | If a field is common to all variants, then the getters and setters are _total_ and return `&T` 39 | and `&mut T` respectively, where `T` is the type of the field. 40 | 41 | If a field is part of some variants but not others, then the getters and 42 | setters are _partial_ and return `Result<&T, E>` and `Result<&mut T, E>` 43 | respectively. 44 | 45 | Many aspects of the getters and setters can be configured, including their 46 | names, whether they `Copy` and which error type `E` is used. 47 | See [Field attributes](../config/field.md). 48 | 49 | ## Casting methods 50 | 51 | The top-level enum has methods to _cast_ it to each of the variants: 52 | 53 | * `as_{variantname}` returning `Result<&{VariantStruct}, E>`. 54 | * `as_{variantname}_mut` returning `Result<&mut {VariantStruct}, E>`. 55 | 56 | The error type `E` may be controlled by the [`cast_error` attribute](../config/struct.md#cast-error). 57 | 58 | ## Reference methods 59 | 60 | The top-level enum has methods for converting it into the `Ref` and `RefMut` types, which 61 | are described [here](./ref-and-refmut.md). 62 | 63 | * `to_ref` returning `{BaseName}Ref`. 64 | * `to_mut` returning `{BaseName}RefMut`. 65 | 66 | ## `From` implementations 67 | 68 | The top-level enum has `From` implementations for converting (owned) variant structs, i.e. 69 | 70 | * `impl From<{VariantStruct}> for {BaseName}` for all variants 71 | -------------------------------------------------------------------------------- /book/src/codegen/map-macros.md: -------------------------------------------------------------------------------- 1 | # Mapping macros 2 | 3 | To facilitate code that is generic over all variants of a `superstruct`, we generate several 4 | _mapping macros_ with names like `map_foo!` and `map_foo_into_bar!`. 5 | 6 | ## Mapping into `Self` 7 | 8 | For every top-level enum we generate a mapping macro that matches on values of 9 | `Self` and is equipped with a variant constructor for `Self`. 10 | 11 | Consider the following type: 12 | 13 | ```rust 14 | #[superstruct(variants(First, Second)] 15 | struct Foo { 16 | x: u8, 17 | #[only(Second)] 18 | y: u8 19 | } 20 | ``` 21 | 22 | The mapping macro for `Foo` will be: 23 | 24 | ```rust 25 | macro_rules! map_foo { 26 | ($value:expr, $f:expr) => { 27 | match $value { 28 | Foo::First(inner) => f(inner, Foo::First), 29 | Foo::Second(inner) => f(inner, Foo::Second), 30 | } 31 | } 32 | } 33 | ``` 34 | 35 | i.e. `map_foo!` is a macro taking two arguments: 36 | 37 | * `value`: an expression which must be of type `Foo`. 38 | * `f`: a function expression, which takes two arguments `|inner, constructor|` where: 39 | * `inner` is an instance of a variant struct, e.g. `FooFirst`. Note that 40 | its type changes between branches! 41 | * `constructor` is a function from the selected variant struct type to `Foo`. Its type 42 | also changes between branches, and would be e.g. `fn(FooFirst) -> Foo` in the case 43 | of the `First` branch. 44 | 45 | Example usage looks like this: 46 | 47 | ```rust 48 | impl Foo { 49 | fn increase_x(self) -> Self { 50 | map_foo!(self, |inner, constructor| { 51 | inner.x += 1; 52 | constructor(inner) 53 | }) 54 | } 55 | } 56 | ``` 57 | 58 | Although the type of `inner` could be `FooFirst` or `FooSecond`, both have an `x` field, so it is 59 | legal to increment it. The `constructor` is then used to re-construct an instance of `Foo` by 60 | injecting the updated `inner` value. If an invalid closure is provided then the type errors may 61 | be quite opaque. On the other hand, if your code type-checks while using `map!` then you can rest 62 | assured that it is valid (`superstruct` doesn't use any `unsafe` blocks or do any spicy casting). 63 | 64 | > Tip: You don't need to use the constructor argument if you are implementing a straight-forward 65 | > projection on `Self`. Although in some cases you may need to provide a type 66 | > hint to the compiler, like `let _ = constructor(inner)`. 67 | 68 | ## Mapping from `Ref` and `RefMut` 69 | 70 | Mapping macros for `Ref` and `RefMut` are also generated. They take an extra lifetime argument 71 | (supplied as a reference to `_`) as their first argument, which must correspond to the lifetime 72 | on the `Ref`/`RefMut` type. 73 | 74 | Example usage for `Foo`: 75 | 76 | ```rust 77 | impl Foo { 78 | fn get_x<'a>(&'a self) -> &'a u64 { 79 | map_foo_ref!(&'a _, self, |inner, _| { 80 | &inner.x 81 | }) 82 | } 83 | } 84 | ``` 85 | 86 | ## Mapping into other types 87 | 88 | Mappings can also be generated between two `superstruct`s with identically named variants. 89 | 90 | These mapping macros are available for the top-level enum, `Ref` and `RefMut`, and take the same 91 | number of arguments. The only difference is that the constructor will be the constructor for the 92 | type being mapped _into_. 93 | 94 | The name of the mapping macro is `map_X_into_Y!` where `X` is the snake-cased 95 | `Self` type and `Y` is the snake-cased target type. 96 | 97 | Example: 98 | 99 | ```rust 100 | #[superstruct( 101 | variants(A, B), 102 | variant_attributes(derive(Debug, PartialEq, Clone)), 103 | map_into(Thing2), 104 | map_ref_into(Thing2Ref), 105 | map_ref_mut_into(Thing2RefMut) 106 | )] 107 | #[derive(Debug, PartialEq, Clone)] 108 | pub struct Thing1 { 109 | #[superstruct(only(A), partial_getter(rename = "thing2a"))] 110 | thing2: Thing2A, 111 | #[superstruct(only(B), partial_getter(rename = "thing2b"))] 112 | thing2: Thing2B, 113 | } 114 | 115 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Clone)))] 116 | #[derive(Debug, PartialEq, Clone)] 117 | pub struct Thing2 { 118 | x: u64, 119 | } 120 | 121 | fn thing1_to_thing2(thing1: Thing1) -> Thing2 { 122 | map_thing1_into_thing2!(thing1, |inner, cons| { cons(inner.thing2) }) 123 | } 124 | 125 | fn thing1_ref_to_thing2_ref<'a>(thing1: Thing1Ref<'a>) -> Thing2Ref<'a> { 126 | map_thing1_ref_into_thing2_ref!(&'a _, thing1, |inner, cons| { cons(&inner.thing2) }) 127 | } 128 | 129 | fn thing1_ref_mut_to_thing2_ref_mut<'a>(thing1: Thing1RefMut<'a>) -> Thing2RefMut<'a> { 130 | map_thing1_ref_mut_into_thing2_ref_mut!(&'a _, thing1, |inner, cons| { 131 | cons(&mut inner.thing2) 132 | }) 133 | } 134 | ``` 135 | 136 | ## Naming 137 | 138 | Type names are converted from `CamelCase` to `snake_case` on a best-effort basis. E.g. 139 | 140 | * `SignedBeaconBlock` -> `map_signed_beacon_block!` 141 | * `NetworkDht` -> `map_network_dht!` 142 | 143 | The current algorithm is quite simplistic and may produce strange names if it encounters 144 | repeated capital letters. Please open an issue on GitHub if you have suggestions on how to 145 | improve this! 146 | 147 | ## Limitations 148 | 149 | * Presently only pure mapping functions are supported. The type-hinting hacks make it hard to 150 | support proper closures. 151 | * Sometimes type-hints are required, e.g. `let _ = constructor(inner)`. 152 | * Macros are scoped per-module, so you need to be more mindful of name collisions than when 153 | defining regular types. 154 | -------------------------------------------------------------------------------- /book/src/codegen/meta-variants.md: -------------------------------------------------------------------------------- 1 | # Meta variant structs and enums 2 | 3 | Meta variants are an optional feature, useful for scenarios where you'd want nested 4 | enums at the top-level. structs will be created for all combinations of `meta_variants` 5 | and `variants`, names in the format `{BaseName}{MetaVariantName}{VariantName}`. 6 | Additionally, enums will be created for each `meta_variant` named `{BaseName}{MetaVariantName}`. 7 | 8 | For example: 9 | 10 | ```rust,no_run,no_playground 11 | #[superstruct(meta_variants(Baz, Qux), variants(Foo, Bar))] 12 | struct MyStruct { 13 | name: String, 14 | #[superstruct(only(Foo))] 15 | location: u16, 16 | #[superstruct(meta_only(Baz))] 17 | score: u64, 18 | #[superstruct(only(Bar), meta_only(Qux))] 19 | id: usize, 20 | } 21 | ``` 22 | 23 | Here the `BaseName` is `MyStruct` and there are two variants in the meta-enum called 24 | `Baz` and `Qux`. 25 | 26 | The generated enums are: 27 | 28 | ```rust,no_run,no_playground 29 | enum MyStruct { 30 | Baz(MyStructBaz), 31 | Qux(MyStructQux), 32 | } 33 | 34 | enum MyStructBaz { 35 | Foo(MyStructBazFoo), 36 | Bar(MyStructBazBar), 37 | } 38 | 39 | enum MyStructQux { 40 | Foo(MyStructQuxFoo), 41 | Bar(MyStructQuxBar), 42 | } 43 | ``` 44 | 45 | The generated variant structs are: 46 | 47 | ```rust,no_run,no_playground 48 | struct MyStructBazFoo { 49 | name: String, 50 | location: u16, 51 | score: u64, 52 | } 53 | 54 | struct MyStructBazBar { 55 | name: String, 56 | score: u64, 57 | } 58 | 59 | struct MyStructQuxFoo { 60 | name: String, 61 | location: u16, 62 | } 63 | 64 | struct MyStructQuxBar { 65 | name: String, 66 | id: usize, 67 | } 68 | ``` 69 | 70 | Note how the `only` attribute still applies, and a new `meta_only` attribute can be used to 71 | control the presence of fields in each meta variant. 72 | 73 | For more information see [Struct attributes](../config/struct.md). 74 | -------------------------------------------------------------------------------- /book/src/codegen/ref-and-refmut.md: -------------------------------------------------------------------------------- 1 | # `Ref` and `RefMut` 2 | 3 | SuperStruct generates two reference-like structs which are designed to simplify working with nested 4 | `superstruct` types. 5 | 6 | The immutable reference type is named `{BaseName}Ref` and has all of the immutable getter methods 7 | from the top-level enum. 8 | 9 | The mutable reference type is named `{BaseName}RefMut` and has all of the mutable getter methods 10 | from the top-level enum. 11 | 12 | Consider the `MyStruct` example again: 13 | 14 | ```rust,no_run,no_playground 15 | #[superstruct(variants(Foo, Bar))] 16 | struct MyStruct { 17 | name: String, 18 | #[superstruct(only(Foo))] 19 | location: u16, 20 | } 21 | ``` 22 | 23 | The generated `Ref` types look like this: 24 | 25 | ```rust,no_run,no_playground 26 | enum MyStructRef<'a> { 27 | Foo(&'a MyStructFoo), 28 | Bar(&'a MyStructBar), 29 | } 30 | 31 | enum MyStructRefMut<'a> { 32 | Foo(&'a mut MyStructFoo), 33 | Bar(&'a mut MyStructFoo), 34 | } 35 | ``` 36 | 37 | The reason these types can be useful (particularly with nesting) is that they do not require a full 38 | reference to a `MyStruct` in order to construct: a reference to a single variant struct will suffice. 39 | 40 | ## Trait Implementations 41 | 42 | ### `Copy` 43 | 44 | Each `Ref` type is `Copy`, just like an ordinary `&T`. 45 | 46 | ### `From` 47 | 48 | The `Ref` type has `From` implementations that allow converting from references to variants 49 | or references to the top-level enum type, i.e. 50 | 51 | - `impl From<&'a {VariantStruct}> for {BaseName}Ref<'a>` for all variants. 52 | - `impl From<&'a {BaseName}> for {BaseName}Ref<'a>` (same as `to_ref()`). 53 | 54 | ## Example 55 | 56 | Please see [`examples/nested.rs`](../rustdoc/src/nested/nested.rs.html) and its 57 | generated [documentation](../rustdoc/nested/). 58 | -------------------------------------------------------------------------------- /book/src/codegen/variant-structs.md: -------------------------------------------------------------------------------- 1 | # Variant structs 2 | 3 | The most basic items generated by SuperStruct are the variant structs. For each 4 | variant listed in the top-level `superstruct(variants(..)` list, a struct with 5 | the name `{BaseName}{VariantName}` will be created. For example: 6 | 7 | ```rust,no_run,no_playground 8 | #[superstruct(variants(Foo, Bar))] 9 | struct MyStruct { 10 | name: String, 11 | #[superstruct(only(Foo))] 12 | location: u16, 13 | } 14 | ``` 15 | 16 | Here the `BaseName` is `MyStruct` and there are two variants called `Foo` and `Bar`. 17 | 18 | The generated variant structs are: 19 | 20 | ```rust,no_run,no_playground 21 | struct MyStructFoo { 22 | name: String, 23 | location: u16, 24 | } 25 | 26 | struct MyStructBar { 27 | name: String, 28 | } 29 | ``` 30 | 31 | Note how the `only` attribute controls the presence of fields in each variant. 32 | For more information see [Struct attributes](../config/struct.md). 33 | 34 | The variant structs are unified as part of the [top-level enum](./enum.md). 35 | -------------------------------------------------------------------------------- /book/src/config.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | SuperStruct is a procedural macro, and is configured by `superstruct` attributes on the 4 | type being defined. 5 | 6 | * [Struct attributes](./config/struct.md) are applied to the top-level type and configure 7 | properties relevant to that, as well as defaults for error types. 8 | * [Field attributes](./config/field.md) are applied to each struct field and determine 9 | the fields of variants, as well as the characteristics of getters and setters. 10 | -------------------------------------------------------------------------------- /book/src/config/field.md: -------------------------------------------------------------------------------- 1 | # Field attributes 2 | 3 | Field attributes may be applied to fields within a `struct` that has a `superstruct` attribute 4 | to it at the top-level. 5 | 6 | All attributes are optional. 7 | 8 | ## Only 9 | 10 | ``` 11 | #[superstruct(only(A, B, ...))] 12 | ``` 13 | 14 | Define the list of variants that this field is a member of. 15 | 16 | The `only` attribute is currently the only way that different variants are 17 | created. 18 | 19 | The selected variants should be a subset of the variants defined in the top-level 20 | [`variants`](./struct.md#variants) attribute. 21 | 22 | **Format**: 1+ comma-separated identifiers. 23 | 24 | ## Getter 25 | 26 | ``` 27 | #[superstruct(getter(copy, ..))] 28 | #[superstruct(getter(no_mut, ..))] 29 | #[superstruct(getter(rename = "..", ..))] 30 | ``` 31 | 32 | Customise the implementation of the [getter functions](../codegen/enum.md#getters-and-setters) for 33 | this field. 34 | 35 | This attribute can only be applied to **common** fields (i.e. ones with no `only` attribute). 36 | 37 | All of the sub-attributes `copy`, `no_mut` and `rename` are optional and any subset of them 38 | may be applied in a single attribute, e.g. `#[superstruct(getter(copy, no_mut))]` is valid. 39 | 40 | * `copy`: return `T` rather than `&T` where `T` is the type of the field. `T` must be `Copy` 41 | or the generated code will fail to typecheck. 42 | * `no_mut`: do not generate a mutating getter with `_mut` suffix. 43 | * `rename = "name"`: rename the immutable getter to `name()` and the mutable getter to `name_mut()` 44 | (if enabled). 45 | 46 | ## Partial getter 47 | 48 | ``` 49 | #[superstruct(partial_getter(copy, ..))] 50 | #[superstruct(partial_getter(no_mut, ..))] 51 | #[superstruct(partial_getter(rename = "..", ..))] 52 | ``` 53 | 54 | Customise the implementation of the [partial getter 55 | functions](../codegen/enum.md#getters-and-setters) for this field. 56 | 57 | This attribute can only be applied to **_non_-common** fields (i.e. ones _with_ an `only` attribute). 58 | 59 | All of the sub-attributes `copy`, `no_mut` and `rename` are optional and any subset of them 60 | may be applied in a single attribute, e.g. `#[superstruct(partial_getter(copy, no_mut))]` is valid. 61 | 62 | * `copy`: return `Result` rather than `Result<&T, E>` where `T` is the type of the field. `T` 63 | must be `Copy` or the generated code will fail to typecheck. 64 | * `no_mut`: do not generate a mutating getter with `_mut` suffix. 65 | * `rename = "name"`: rename the immutable partial getter to `name()` and the mutable partial getter 66 | to `name_mut()` (if enabled). 67 | 68 | The error type for partial getters can currently only be configured on a per-struct basis 69 | via the [`partial_getter_error`](./struct.md#partial-getter-error) attribute, although this may 70 | change in a future release. 71 | 72 | ## No Getter 73 | Disable the generation of (partial) getter functions for this field. 74 | This can be used for when two fields have the same name but different types: 75 | 76 | ```rust 77 | #[superstruct(variants(A, B))] 78 | struct NoGetter { 79 | #[superstruct(only(A), no_getter)] 80 | pub x: u64, 81 | #[superstruct(only(B), no_getter)] 82 | pub x: String, 83 | } 84 | ``` 85 | 86 | ## Flatten 87 | 88 | ``` 89 | #[superstruct(flatten)] 90 | ``` 91 | 92 | This attribute can only be applied to enum fields with variants that match each variant of the 93 | superstruct. This is useful for nesting superstructs whose variant types should be linked. 94 | 95 | This will automatically create a partial getter for each variant. The following two examples are equivalent. 96 | 97 | Using `flatten`: 98 | ```rust 99 | #[superstruct(variants(A, B))] 100 | struct InnerMessage { 101 | pub x: u64, 102 | pub y: u64, 103 | } 104 | 105 | #[superstruct(variants(A, B))] 106 | struct Message { 107 | #[superstruct(flatten)] 108 | pub inner: InnerMessage, 109 | } 110 | ``` 111 | Equivalent without `flatten`: 112 | ```rust 113 | #[superstruct(variants(A, B))] 114 | struct InnerMessage { 115 | pub x: u64, 116 | pub y: u64, 117 | } 118 | 119 | #[superstruct(variants(A, B))] 120 | struct Message { 121 | #[superstruct(only(A), partial_getter(rename = "inner_a"))] 122 | pub inner: InnerMessageA, 123 | #[superstruct(only(B), partial_getter(rename = "inner_b"))] 124 | pub inner: InnerMessageB, 125 | } 126 | ``` 127 | 128 | If you wish to only flatten into only a subset of variants, you can define them like so: 129 | 130 | ```rust 131 | #[superstruct(variants(A, B))] 132 | struct InnerMessage { 133 | pub x: u64, 134 | pub y: u64, 135 | } 136 | 137 | #[superstruct(variants(A, B, C))] 138 | struct Message { 139 | #[superstruct(flatten(A,B))] 140 | pub inner: InnerMessage, 141 | } 142 | ``` 143 | -------------------------------------------------------------------------------- /book/src/config/struct.md: -------------------------------------------------------------------------------- 1 | # Struct attributes 2 | 3 | The following attributes may be used in a `superstruct` macro invocation on a 4 | `struct` item. All attributes are optional unless stated otherwise. 5 | 6 | ## Variants 7 | 8 | ``` 9 | #[superstruct(variants(A, B, ...))] 10 | ``` 11 | 12 | Define the list of variants that this type has. 13 | See [variant structs](../codegen/variant-structs.md). 14 | 15 | The `variants` attribute is _not optional_. 16 | 17 | **Format**: 1+ comma-separated identifiers. 18 | 19 | ## Cast error 20 | 21 | ``` 22 | #[superstruct(cast_error(ty = "..", expr = ".."))] 23 | ``` 24 | 25 | Define the error type to be returned from [casting methods](../codegen/enum.md#casting-methods). 26 | 27 | The expression must be of the given error type, and capable of being evaluated without any 28 | context (it is _not_ a closure). 29 | 30 | **Format**: quoted type for `ty`, quoted expression for `expr` 31 | 32 | ## Partial getter error 33 | 34 | ``` 35 | #[superstruct(cast_error(ty = "..", expr = ".."))] 36 | ``` 37 | 38 | Define the error type to be returned from [partial getter 39 | methods](../codegen/enum.md#getters-and-setters). 40 | 41 | The expression must be of the given error type, and capable of being evaluated without any 42 | context (it is _not_ a closure). 43 | 44 | **Format**: quoted type for `ty`, quoted expression for `expr` 45 | 46 | ## Variant attributes 47 | 48 | ``` 49 | #[superstruct(variant_attributes(...))] 50 | ``` 51 | 52 | Provide a list of attributes to be applied verbatim to each variant struct definition. 53 | 54 | This can be used to derive traits, perform conditional compilation, etc. 55 | 56 | **Format**: any. 57 | 58 | ## Specific variant attributes 59 | 60 | ``` 61 | #[superstruct(specific_variant_attributes(A(...), B(...), ...))] 62 | ``` 63 | 64 | Similar to `variant_attributes`, but applies the attributes _only_ to the named variants. This 65 | is useful if e.g. one variant needs to derive a trait which the others cannot, or if another 66 | procedural macro is being invoked on the variant struct which requires different parameters. 67 | 68 | **Format**: zero or more variant names, with variant attributes nested in parens 69 | 70 | ## `Ref` attributes 71 | 72 | ``` 73 | #[superstruct(ref_attributes(...))] 74 | ``` 75 | 76 | Provide a list of attributes to be applied verbatim to the generated `Ref` type. 77 | 78 | **Format**: any. 79 | 80 | ## `RefMut` attributes 81 | 82 | ``` 83 | #[superstruct(ref_mut_attributes(...))] 84 | ``` 85 | 86 | Provide a list of attributes to be applied verbatim to the generated `RefMut` type. 87 | 88 | **Format**: any. 89 | 90 | ## No enum 91 | 92 | ``` 93 | #[superstruct(no_enum)] 94 | ``` 95 | 96 | Disable generation of the top-level enum, and all code except the 97 | [variant structs](../codegen/variant-structs.md). 98 | 99 | ## Map Into 100 | 101 | ``` 102 | #[map_into(ty1, ty2, ..)] 103 | #[map_ref_into(ty1, ty2, ..)] 104 | #[map_ref_mut_into(ty1, ty2, ..)] 105 | ``` 106 | 107 | Generate mapping macros from the top-level enum, the `Ref` type or the `RefMut` type as appropriate. 108 | 109 | Please see the documentation on [Mapping into other types](./codegen/map-macros.md#mapping-into-other-types) 110 | for an explanation of how these macros operate. 111 | 112 | **Format**: one or more `superstruct` type names 113 | 114 | ## Meta variants 115 | 116 | ``` 117 | #[superstruct(meta_variants(A, B, ...), variants(C, D, ...))] 118 | ``` 119 | 120 | Generate a two-dimensional superstruct. 121 | See [meta variant structs](../codegen/meta-variants.md). 122 | 123 | The `meta_variants` attribute is optional. 124 | 125 | **Format**: 1+ comma-separated identifiers. 126 | -------------------------------------------------------------------------------- /book/src/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | SuperStruct is a Rust library for working with versioned data. It allows you to define and operate 4 | on _variants_ of a `struct` which share some fields in common. 5 | 6 | As an example, imagine you're working on a program that accepts a `Request` struct from the user. 7 | In the first version of the program you only allow users to specify a `start: u16` field: 8 | 9 | ```rust,no_run,no_playground 10 | pub struct Request { 11 | start: u16, 12 | } 13 | ``` 14 | 15 | After a while you realise that it would be nice if users could also specify an `end: u16` in their 16 | requests, so you would like to change the definition of `Request` to: 17 | 18 | ```rust,no_run,no_playground 19 | pub struct Request { 20 | start: u16, 21 | end: u16, 22 | } 23 | ``` 24 | 25 | Now imagine that your program needs to work with old versions of `Request` as well as new, i.e. 26 | it needs to be backwards-compatible. This is reasonably common when databases are involved and 27 | you need to write schema migrations, or when working with network protocols. 28 | 29 | SuperStruct allows you to define _both_ versions of the `Request` with a single definition, and 30 | also generates an enum to unify them: 31 | 32 | ```rust,no_run,noplayground 33 | {{#include ../../examples/request.rs}} 34 | ``` 35 | 36 | The `superstruct` definition generates: 37 | 38 | * Two structs `RequestV1` and `RequestV2` where the `end` field is only present in `RequestV2`. 39 | * An enum `Request` with variants `V1` and `V2` wrapping `RequestV1` and `RequestV2` respectively. 40 | * A getter function on `Request` for the shared `start` field, e.g. `r1.start()`. 41 | * A _partial_ getter function returning `Result<&u16, ()>` for `end`, e.g. `r2.end()`. 42 | * Lots of other useful goodies that are covered in the [Codegen](./codegen.md) section of the book. 43 | 44 | ## When _should_ you use SuperStruct? 45 | 46 | * If you want to avoid duplication when defining multiple related structs. 47 | * If you are considering manually writing getters to extract common fields from an enum. 48 | * If you are considering writing traits to unify types with fields in common. 49 | 50 | ## When should you _not_ use SuperStruct? 51 | 52 | * If you can get away with just using an `Option` field. In our example, `Request` could define 53 | `end: Option`. 54 | * If you can achieve backwards compatible (de)serialization through clever use of `serde` macros. 55 | 56 | ## What next? 57 | 58 | * Check out the [Code Generation](./codegen.md) docs. 59 | * Check out the [Configuration](./config.md) docs for information on how to 60 | control `superstruct`'s behaviour, including renaming getters, working with 61 | `Copy` types, etc. 62 | -------------------------------------------------------------------------------- /book/src/setup.md: -------------------------------------------------------------------------------- 1 | # Setup 2 | 3 | To use SuperStruct in your project add `superstruct` as a dependency in your `Cargo.toml`: 4 | 5 | ```toml 6 | superstruct = "0.4.0" 7 | ``` 8 | 9 | For the latest published version please consult [`crates.io`](https://crates.io/crates/superstruct). 10 | 11 | ---- 12 | 13 | To use SuperStruct, import the `superstruct` procedural macro with `use superstruct::superstruct`, 14 | like so: 15 | 16 | ```rust,no_run,noplayground 17 | {{#include ../../examples/request.rs}} 18 | ``` 19 | 20 | For more information on this example see the [Introduction](./intro.md). 21 | -------------------------------------------------------------------------------- /examples/customer.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use superstruct::superstruct; 3 | 4 | #[superstruct( 5 | variants(V1, V2, V3), 6 | variant_attributes(derive(Deserialize, Serialize)) 7 | )] 8 | #[derive(Deserialize, Serialize)] 9 | #[serde(untagged)] 10 | pub struct Customer { 11 | pub name: String, 12 | #[superstruct(only(V1), partial_getter(rename = "age_v1"))] 13 | pub age: String, 14 | #[superstruct(only(V2), partial_getter(rename = "age_v2"))] 15 | pub age: u64, 16 | #[superstruct(only(V3))] 17 | pub dob: u64, 18 | #[superstruct(only(V2, V3))] 19 | pub favourite_colour: String, 20 | } 21 | 22 | fn main() { 23 | let customer = Customer::V3(CustomerV3 { 24 | name: "Michael".into(), 25 | dob: 0, 26 | favourite_colour: "purple".into(), 27 | }); 28 | assert_eq!(customer.name(), "Michael"); 29 | assert_eq!(customer.dob(), Ok(&0)); 30 | assert_eq!(customer.favourite_colour().unwrap(), "purple"); 31 | } 32 | -------------------------------------------------------------------------------- /examples/nested.rs: -------------------------------------------------------------------------------- 1 | use superstruct::superstruct; 2 | 3 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))] 4 | #[derive(Debug, Clone)] 5 | pub struct Inner { 6 | pub both: &'static str, 7 | #[superstruct(only(A), partial_getter(copy))] 8 | pub only_a: &'static str, 9 | } 10 | 11 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, Clone)))] 12 | #[derive(Debug, Clone)] 13 | pub struct Outer { 14 | #[superstruct(only(A), partial_getter(rename = "inner_a"))] 15 | pub inner: InnerA, 16 | #[superstruct(only(B), partial_getter(rename = "inner_b"))] 17 | pub inner: InnerB, 18 | } 19 | 20 | impl Outer { 21 | pub fn inner(&self) -> InnerRef<'_> { 22 | match self { 23 | Outer::A(a) => InnerRef::A(&a.inner), 24 | Outer::B(b) => InnerRef::B(&b.inner), 25 | } 26 | } 27 | 28 | pub fn inner_mut(&mut self) -> InnerRefMut<'_> { 29 | match self { 30 | Outer::A(a) => InnerRefMut::A(&mut a.inner), 31 | Outer::B(b) => InnerRefMut::B(&mut b.inner), 32 | } 33 | } 34 | } 35 | 36 | #[cfg_attr(test, test)] 37 | fn main() { 38 | let inner_a = InnerA { 39 | both: "hello", 40 | only_a: "world", 41 | }; 42 | let inner_b = InnerB { both: "hello" }; 43 | 44 | let mut a = Outer::A(OuterA { 45 | inner: inner_a.clone(), 46 | }); 47 | let b = Outer::B(OuterB { 48 | inner: inner_b.clone(), 49 | }); 50 | 51 | assert_eq!(a.inner_a().unwrap().both, b.inner_b().unwrap().both); 52 | assert_eq!(a.inner().both(), b.inner().both()); 53 | assert_eq!(a.inner_a().unwrap().only_a, "world"); 54 | 55 | *a.inner_mut().only_a_mut().unwrap() = "moon"; 56 | assert_eq!(a.inner().only_a().unwrap(), "moon"); 57 | } 58 | -------------------------------------------------------------------------------- /examples/request.rs: -------------------------------------------------------------------------------- 1 | use superstruct::superstruct; 2 | 3 | #[superstruct(variants(V1, V2))] 4 | pub struct Request { 5 | pub start: u16, 6 | #[superstruct(only(V2))] 7 | pub end: u16, 8 | } 9 | 10 | #[cfg_attr(test, test)] 11 | fn main() { 12 | let r1 = Request::V1(RequestV1 { start: 0 }); 13 | let r2 = Request::V2(RequestV2 { start: 0, end: 10 }); 14 | 15 | assert_eq!(r1.start(), r2.start()); 16 | assert_eq!(r1.end(), Err(())); 17 | assert_eq!(r2.end(), Ok(&10)); 18 | } 19 | -------------------------------------------------------------------------------- /src/attributes.rs: -------------------------------------------------------------------------------- 1 | //! Utilities to help with parsing configuration attributes. 2 | use darling::{export::NestedMeta, Error, FromMeta}; 3 | use syn::Ident; 4 | 5 | /// Parse a list of nested meta items. 6 | /// 7 | /// Useful for passing through attributes intended for other macros. 8 | #[derive(Debug)] 9 | pub struct NestedMetaList { 10 | pub metas: Vec, 11 | } 12 | 13 | impl FromMeta for NestedMetaList { 14 | fn from_list(items: &[NestedMeta]) -> Result { 15 | Ok(Self { 16 | metas: items.to_vec(), 17 | }) 18 | } 19 | } 20 | 21 | /// List of identifiers implementing `FromMeta`. 22 | /// 23 | /// Useful for imposing ordering, unlike the `HashMap` options provided by `darling`. 24 | #[derive(Debug, Default, Clone)] 25 | pub struct IdentList { 26 | pub idents: Vec, 27 | } 28 | 29 | impl FromMeta for IdentList { 30 | fn from_list(items: &[NestedMeta]) -> Result { 31 | let idents = items 32 | .iter() 33 | .map(|nested_meta| { 34 | let meta = match nested_meta { 35 | NestedMeta::Meta(m) => m, 36 | NestedMeta::Lit(l) => { 37 | return Err(Error::custom(format!( 38 | "expected ident, got literal: {:?}", 39 | l 40 | ))) 41 | } 42 | }; 43 | let path = meta.path(); 44 | path.get_ident() 45 | .cloned() 46 | .ok_or(Error::custom(format!("can't parse as ident: {:?}", path))) 47 | }) 48 | .collect::>()?; 49 | Ok(Self { idents }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/from.rs: -------------------------------------------------------------------------------- 1 | //! Generate `From` implementations to convert variants to the top-level enum. 2 | use quote::quote; 3 | use syn::{Ident, ImplGenerics, Lifetime, TypeGenerics, WhereClause}; 4 | 5 | pub fn generate_from_variant_trait_impl( 6 | type_name: &Ident, 7 | impl_generics: &ImplGenerics, 8 | ty_generics: &TypeGenerics, 9 | where_clause: &Option<&WhereClause>, 10 | variant_name: &Ident, 11 | struct_name: &Ident, 12 | ) -> proc_macro2::TokenStream { 13 | quote! { 14 | impl #impl_generics From<#struct_name #ty_generics> for #type_name #ty_generics #where_clause { 15 | fn from(variant: #struct_name #ty_generics) -> Self { 16 | Self::#variant_name(variant) 17 | } 18 | } 19 | } 20 | } 21 | 22 | #[allow(clippy::too_many_arguments)] 23 | pub fn generate_from_variant_trait_impl_for_ref( 24 | ref_ty_name: &Ident, 25 | ref_ty_lifetime: &Lifetime, 26 | ref_impl_generics: &ImplGenerics, 27 | ref_ty_generics: &TypeGenerics, 28 | ty_generics: &TypeGenerics, 29 | where_clause: &Option<&WhereClause>, 30 | variant_name: &Ident, 31 | struct_name: &Ident, 32 | ) -> proc_macro2::TokenStream { 33 | quote! { 34 | impl #ref_impl_generics From<&#ref_ty_lifetime #struct_name #ty_generics> for #ref_ty_name #ref_ty_generics #where_clause { 35 | fn from(variant: &#ref_ty_lifetime #struct_name #ty_generics) -> Self { 36 | Self::#variant_name(variant) 37 | } 38 | } 39 | } 40 | } 41 | 42 | pub fn generate_from_enum_trait_impl_for_ref( 43 | ty_name: &Ident, 44 | ty_generics: &TypeGenerics, 45 | ref_ty_name: &Ident, 46 | ref_ty_lifetime: &Lifetime, 47 | ref_impl_generics: &ImplGenerics, 48 | ref_ty_generics: &TypeGenerics, 49 | where_clause: &Option<&WhereClause>, 50 | ) -> proc_macro2::TokenStream { 51 | quote! { 52 | impl #ref_impl_generics From<&#ref_ty_lifetime #ty_name #ty_generics> for #ref_ty_name #ref_ty_generics #where_clause { 53 | fn from(ref_to_enum: &#ref_ty_lifetime #ty_name #ty_generics) -> Self { 54 | ref_to_enum.to_ref() 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | iter::{self, FromIterator}, 4 | }; 5 | 6 | use attributes::{IdentList, NestedMetaList}; 7 | use darling::{export::NestedMeta, util::Override, FromMeta}; 8 | use from::{ 9 | generate_from_enum_trait_impl_for_ref, generate_from_variant_trait_impl, 10 | generate_from_variant_trait_impl_for_ref, 11 | }; 12 | use itertools::Itertools; 13 | use macros::generate_all_map_macros; 14 | use proc_macro::TokenStream; 15 | use proc_macro2::{Span, TokenStream as TokenStream2}; 16 | use quote::{format_ident, quote, ToTokens}; 17 | use syn::{ 18 | parse_macro_input, Attribute, Expr, Field, GenericParam, Ident, ItemStruct, Lifetime, 19 | LifetimeParam, Type, TypeGenerics, TypeParamBound, 20 | }; 21 | 22 | mod attributes; 23 | mod from; 24 | mod macros; 25 | mod naming; 26 | mod utils; 27 | 28 | /// Top-level configuration via the `superstruct` attribute. 29 | #[derive(Debug, FromMeta)] 30 | struct StructOpts { 31 | /// List of meta variant names of the superstruct being derived. 32 | #[darling(default)] 33 | meta_variants: Option, 34 | /// List of variant names of the superstruct being derived. 35 | variants: IdentList, 36 | /// List of attributes to apply to the variant structs. 37 | #[darling(default)] 38 | variant_attributes: Option, 39 | /// List of attributes to apply to a selection of named variant structs. 40 | #[darling(default)] 41 | specific_variant_attributes: Option>, 42 | /// List of attributes to apply to the generated Ref type. 43 | #[darling(default)] 44 | ref_attributes: Option, 45 | /// List of attributes to apply to the generated RefMut type. 46 | #[darling(default)] 47 | ref_mut_attributes: Option, 48 | /// Error type and expression to use for casting methods. 49 | #[darling(default)] 50 | cast_error: ErrorOpts, 51 | /// Error type and expression to use for partial getter methods. 52 | #[darling(default)] 53 | partial_getter_error: ErrorOpts, 54 | /// Turn off the generation of the top-level enum that binds the variants together. 55 | #[darling(default)] 56 | no_enum: bool, 57 | /// Turn off the generation of the map macros. 58 | #[darling(default)] 59 | no_map_macros: bool, 60 | /// List of other superstruct types to generate (owned) mappings into. 61 | #[darling(default)] 62 | map_into: Option, 63 | /// List of other superstruct types to generate mappings into from Ref. 64 | #[darling(default)] 65 | map_ref_into: Option, 66 | /// List of other superstruct types to generate mappings into from RefMut. 67 | #[darling(default)] 68 | map_ref_mut_into: Option, 69 | } 70 | 71 | /// Field-level configuration. 72 | #[derive(Debug, Default, FromMeta)] 73 | struct FieldOpts { 74 | // TODO: When we update darling, we can replace `Override` 75 | // with a custom enum and use `#[darling(word)]` on the variant 76 | // we want to use for `#[superstruct(flatten)]` (no variants specified). 77 | #[darling(default)] 78 | flatten: Option>>, 79 | #[darling(default)] 80 | only: Option>, 81 | #[darling(default)] 82 | meta_only: Option>, 83 | #[darling(default)] 84 | getter: Option, 85 | #[darling(default)] 86 | partial_getter: Option, 87 | no_getter: darling::util::Flag, 88 | } 89 | 90 | /// Getter configuration for a specific field 91 | #[derive(Debug, Default, FromMeta)] 92 | struct GetterOpts { 93 | #[darling(default)] 94 | copy: bool, 95 | #[darling(default)] 96 | no_mut: bool, 97 | #[darling(default)] 98 | rename: Option, 99 | } 100 | 101 | #[derive(Debug, Default, FromMeta)] 102 | struct ErrorOpts { 103 | #[darling(default)] 104 | ty: Option, 105 | #[darling(default)] 106 | expr: Option, 107 | } 108 | 109 | impl ErrorOpts { 110 | fn parse(&self) -> Option<(Type, Expr)> { 111 | let err_ty_str = self.ty.as_ref()?; 112 | let err_ty: Type = syn::parse_str(err_ty_str).expect("error type not valid"); 113 | let err_expr_str = self 114 | .expr 115 | .as_ref() 116 | .expect("must provide an error expr with error ty"); 117 | let err_expr: Expr = syn::parse_str(err_expr_str).expect("error expr not valid"); 118 | Some((err_ty, err_expr)) 119 | } 120 | 121 | fn build_result_type( 122 | &self, 123 | ret_ty: impl ToTokens, 124 | ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) { 125 | if let Some((err_ty, err_expr)) = self.parse() { 126 | (quote! { Result<#ret_ty, #err_ty> }, quote! { #err_expr }) 127 | } else { 128 | (quote! { Result<#ret_ty, ()> }, quote! { () }) 129 | } 130 | } 131 | } 132 | 133 | /// All data about a field, including its type & config from attributes. 134 | #[derive(Debug)] 135 | struct FieldData { 136 | name: Ident, 137 | field: Field, 138 | only_combinations: Vec, 139 | getter_opts: GetterOpts, 140 | partial_getter_opts: GetterOpts, 141 | no_getter: bool, 142 | is_common: bool, 143 | } 144 | 145 | impl FieldData { 146 | fn is_common(&self) -> bool { 147 | self.is_common 148 | } 149 | 150 | fn no_getter(&self) -> bool { 151 | self.no_getter 152 | } 153 | 154 | /// Checks whether this field should be included in creating 155 | /// partial getters for the given type name. 156 | fn exists_in_meta(&self, type_name: &Ident) -> bool { 157 | let only_metas = self 158 | .only_combinations 159 | .iter() 160 | .filter_map(|only| only.meta_variant.as_ref()) 161 | .map(ToString::to_string) 162 | .collect::>(); 163 | 164 | if only_metas.is_empty() { 165 | return true; 166 | } 167 | only_metas 168 | .iter() 169 | .any(|only| type_name.to_string().ends_with(only)) 170 | } 171 | } 172 | 173 | #[derive(Hash, Eq, PartialEq, Debug, Clone)] 174 | struct VariantKey { 175 | variant: Ident, 176 | meta_variant: Option, 177 | } 178 | 179 | #[proc_macro_attribute] 180 | pub fn superstruct(args: TokenStream, input: TokenStream) -> TokenStream { 181 | let attr_args = match NestedMeta::parse_meta_list(args.into()) { 182 | Ok(args) => args, 183 | Err(err) => return err.to_compile_error().into(), 184 | }; 185 | let item = parse_macro_input!(input as ItemStruct); 186 | 187 | let type_name = &item.ident; 188 | let visibility = item.vis.clone(); 189 | // Extract the generics to use for the top-level type and all variant structs. 190 | let decl_generics = &item.generics; 191 | // Generics used for the impl block. 192 | let (_, _, where_clause) = &item.generics.split_for_impl(); 193 | 194 | let opts = StructOpts::from_list(&attr_args).unwrap(); 195 | 196 | let mut output_items: Vec = vec![]; 197 | 198 | let mk_struct_name = |variant_key: &VariantKey| { 199 | let VariantKey { 200 | variant, 201 | meta_variant, 202 | } = variant_key; 203 | 204 | if let Some(meta_variant) = meta_variant { 205 | format_ident!("{}{}{}", type_name, meta_variant, variant) 206 | } else { 207 | format_ident!("{}{}", type_name, variant) 208 | } 209 | }; 210 | 211 | let variant_names = &opts.variants.idents; 212 | let meta_variant_names = &opts 213 | .meta_variants 214 | .clone() 215 | .map(|mv| mv.idents.into_iter().map(Some).collect_vec()) 216 | .unwrap_or(vec![None]); 217 | let variant_combinations = variant_names 218 | .iter() 219 | .cloned() 220 | .cartesian_product(meta_variant_names.iter().cloned()) 221 | .map(|(v, mv)| VariantKey { 222 | variant: v, 223 | meta_variant: mv, 224 | }); 225 | 226 | let struct_names = variant_combinations 227 | .clone() 228 | .map(|key| mk_struct_name(&key)) 229 | .collect_vec(); 230 | 231 | // Vec of field data. 232 | let mut fields = vec![]; 233 | // Map from variant or meta variant to variant fields. 234 | let mut variant_fields = 235 | HashMap::<_, _>::from_iter(variant_combinations.clone().zip(iter::repeat(vec![]))); 236 | 237 | for field in &item.fields { 238 | let name = field.ident.clone().expect("named fields only"); 239 | let field_opts = field 240 | .attrs 241 | .iter() 242 | .filter(|attr| is_superstruct_attr(attr)) 243 | .map(|attr| FieldOpts::from_meta(&attr.meta).unwrap()) 244 | .next() 245 | .unwrap_or_default(); 246 | 247 | // Check for conflicting attributes. 248 | check_for_conflicting_superstruct_attrs(&field.attrs); 249 | 250 | // Drop the field-level superstruct attributes 251 | let mut output_field = field.clone(); 252 | output_field.attrs = discard_superstruct_attrs(&output_field.attrs); 253 | 254 | // Add the field to the `variant_fields` map for all applicable variants. 255 | let field_variants = field_opts.only.as_ref().map_or_else( 256 | || variant_names.clone(), 257 | |only| only.keys().cloned().collect_vec(), 258 | ); 259 | let field_meta_variants = field_opts.meta_only.as_ref().map_or_else( 260 | || meta_variant_names.clone(), 261 | |meta_only| meta_only.keys().cloned().map(Some).collect_vec(), 262 | ); 263 | 264 | // Field is common if it is part of every meta variant AND every variant. 265 | let is_common_meta = opts 266 | .meta_variants 267 | .as_ref() 268 | .is_none_or(|struct_meta_variants| { 269 | struct_meta_variants.idents.len() == field_meta_variants.len() 270 | }); 271 | let is_common = field_variants.len() == variant_names.len() && is_common_meta; 272 | 273 | let only_combinations = field_variants 274 | .iter() 275 | .cartesian_product(field_meta_variants.iter()); 276 | 277 | for (variant, meta_variant) in only_combinations.clone() { 278 | variant_fields 279 | .get_mut(&VariantKey { 280 | variant: variant.clone(), 281 | meta_variant: meta_variant.clone(), 282 | }) 283 | .expect("invalid variant name in `only` or `meta_only`") 284 | .push(output_field.clone()); 285 | } 286 | 287 | // Check field opts 288 | if field_opts.only.is_some() && field_opts.getter.is_some() { 289 | panic!("can't configure `only` and `getter` on the same field"); 290 | } else if field_opts.meta_only.is_some() && field_opts.getter.is_some() { 291 | panic!("can't configure `meta_only` and `getter` on the same field"); 292 | } else if field_opts.only.is_none() 293 | && field_opts.meta_only.is_none() 294 | && field_opts.partial_getter.is_some() 295 | { 296 | panic!("can't set `partial_getter` options on common field"); 297 | } else if field_opts.flatten.is_some() && field_opts.only.is_some() { 298 | panic!("can't set `flatten` and `only` on the same field"); 299 | } else if field_opts.flatten.is_some() && field_opts.getter.is_some() { 300 | panic!("can't set `flatten` and `getter` on the same field"); 301 | } else if field_opts.flatten.is_some() && field_opts.partial_getter.is_some() { 302 | panic!("can't set `flatten` and `partial_getter` on the same field"); 303 | } else if field_opts.flatten.is_some() && field_opts.no_getter.is_present() { 304 | panic!("can't set `flatten` and `no_getter` on the same field") 305 | } else if field_opts.getter.is_some() && field_opts.no_getter.is_present() { 306 | panic!("can't set `getter` and `no_getter` on the same field") 307 | } else if field_opts.partial_getter.is_some() && field_opts.no_getter.is_present() { 308 | panic!("can't set `partial_getter` and `no_getter` on the same field") 309 | } 310 | 311 | let getter_opts = field_opts.getter.unwrap_or_default(); 312 | let partial_getter_opts = field_opts.partial_getter.unwrap_or_default(); 313 | 314 | if let Some(flatten_opts) = field_opts.flatten { 315 | for variant_key in variant_combinations.clone() { 316 | let variant = &variant_key.variant; 317 | let meta_variant = variant_key.meta_variant.as_ref(); 318 | 319 | let Some(variant_field_index) = variant_fields 320 | .get(&variant_key) 321 | .expect("invalid variant name") 322 | .iter() 323 | .position(|f| f.ident.as_ref() == Some(&name)) 324 | else { 325 | continue; 326 | }; 327 | 328 | if should_skip( 329 | variant_names, 330 | meta_variant_names, 331 | &flatten_opts, 332 | &variant_key, 333 | ) { 334 | // Remove the field from the field map 335 | let fields = variant_fields 336 | .get_mut(&variant_key) 337 | .expect("invalid variant name"); 338 | fields.remove(variant_field_index); 339 | continue; 340 | } 341 | 342 | // Update the struct name for this variant. 343 | let mut next_variant_field = output_field.clone(); 344 | 345 | let last_segment_mut_ref = match next_variant_field.ty { 346 | Type::Path(ref mut p) => { 347 | &mut p 348 | .path 349 | .segments 350 | .last_mut() 351 | .expect("path should have at least one segment") 352 | .ident 353 | } 354 | _ => panic!("field must be a path"), 355 | }; 356 | 357 | let (next_variant_ty_name, partial_getter_rename) = 358 | if let Some(meta_variant) = meta_variant { 359 | if let Some(meta_only) = field_opts.meta_only.as_ref() { 360 | assert_eq!( 361 | meta_only.len(), 362 | 1, 363 | "when used in combination with flatten, only \ 364 | one meta variant specification is allowed" 365 | ); 366 | assert_eq!( 367 | meta_only.keys().next().unwrap(), 368 | meta_variant, 369 | "flattened meta variant does not match" 370 | ); 371 | ( 372 | format_ident!("{}{}", last_segment_mut_ref.clone(), variant), 373 | format_ident!("{}_{}", name, variant.to_string().to_lowercase()), 374 | ) 375 | } else { 376 | ( 377 | format_ident!( 378 | "{}{}{}", 379 | last_segment_mut_ref.clone(), 380 | meta_variant, 381 | variant 382 | ), 383 | format_ident!( 384 | "{}_{}_{}", 385 | name, 386 | meta_variant.to_string().to_lowercase(), 387 | variant.to_string().to_lowercase() 388 | ), 389 | ) 390 | } 391 | } else { 392 | ( 393 | format_ident!("{}{}", last_segment_mut_ref.clone(), variant), 394 | format_ident!("{}_{}", name, variant.to_string().to_lowercase()), 395 | ) 396 | }; 397 | *last_segment_mut_ref = next_variant_ty_name; 398 | 399 | // Create a partial getter for the field. 400 | let partial_getter_opts = GetterOpts { 401 | rename: Some(partial_getter_rename), 402 | ..<_>::default() 403 | }; 404 | 405 | fields.push(FieldData { 406 | name: name.clone(), 407 | field: next_variant_field.clone(), 408 | // Make sure the field is only accessible from this variant. 409 | only_combinations: vec![variant_key.clone()], 410 | getter_opts: <_>::default(), 411 | partial_getter_opts, 412 | no_getter: false, 413 | is_common: false, 414 | }); 415 | 416 | // Update the variant field map 417 | let fields = variant_fields 418 | .get_mut(&variant_key) 419 | .expect("invalid variant name"); 420 | *fields 421 | .get_mut(variant_field_index) 422 | .expect("invalid field index") = next_variant_field; 423 | } 424 | } else { 425 | fields.push(FieldData { 426 | name, 427 | field: output_field, 428 | only_combinations: only_combinations 429 | .map(|(variant, meta_variant)| VariantKey { 430 | variant: variant.clone(), 431 | meta_variant: meta_variant.clone(), 432 | }) 433 | .collect_vec(), 434 | getter_opts, 435 | partial_getter_opts, 436 | no_getter: field_opts.no_getter.is_present(), 437 | is_common, 438 | }); 439 | } 440 | } 441 | 442 | // Generate structs for all of the variants. 443 | let universal_struct_attributes = opts 444 | .variant_attributes 445 | .as_ref() 446 | .map_or(&[][..], |attrs| &attrs.metas); 447 | 448 | for (variant_key, struct_name) in variant_combinations.zip(struct_names.iter()) { 449 | let fields = &variant_fields[&variant_key]; 450 | 451 | let specific_struct_attributes = opts 452 | .specific_variant_attributes 453 | .as_ref() 454 | .and_then(|sv| sv.get(&variant_key.variant)) 455 | .map_or(&[][..], |attrs| &attrs.metas); 456 | let specific_struct_attributes_meta = opts 457 | .specific_variant_attributes 458 | .as_ref() 459 | .and_then(|sv| variant_key.meta_variant.and_then(|mv| sv.get(&mv))) 460 | .map_or(&[][..], |attrs| &attrs.metas); 461 | let spatt = specific_struct_attributes 462 | .iter() 463 | .chain(specific_struct_attributes_meta.iter()); 464 | 465 | let variant_code = quote! { 466 | #( 467 | #[#universal_struct_attributes] 468 | )* 469 | #( 470 | #[#spatt] 471 | )* 472 | #visibility struct #struct_name #decl_generics #where_clause { 473 | #( 474 | #fields, 475 | )* 476 | } 477 | }; 478 | output_items.push(variant_code.into()); 479 | } 480 | 481 | // If the `no_enum` attribute is set, stop after generating variant structs. 482 | if opts.no_enum { 483 | return TokenStream::from_iter(output_items); 484 | } 485 | 486 | let mut inner_enum_names = vec![]; 487 | 488 | // Generate inner enums if necessary. 489 | for meta_variant in meta_variant_names.iter().flatten() { 490 | let inner_enum_name = format_ident!("{}{}", type_name, meta_variant); 491 | inner_enum_names.push(inner_enum_name.clone()); 492 | let inner_struct_names = variant_names 493 | .iter() 494 | .map(|variant_name| format_ident!("{}{}", inner_enum_name, variant_name)) 495 | .collect_vec(); 496 | generate_wrapper_enums( 497 | &inner_enum_name, 498 | &item, 499 | &opts, 500 | &mut output_items, 501 | variant_names, 502 | &inner_struct_names, 503 | &fields, 504 | false, 505 | ); 506 | } 507 | 508 | // Generate outer enum. 509 | let variant_names = opts 510 | .meta_variants 511 | .as_ref() 512 | .map(|mv| &mv.idents) 513 | .unwrap_or(variant_names); 514 | let struct_names = &opts 515 | .meta_variants 516 | .as_ref() 517 | .map(|_| inner_enum_names) 518 | .unwrap_or(struct_names); 519 | generate_wrapper_enums( 520 | type_name, 521 | &item, 522 | &opts, 523 | &mut output_items, 524 | variant_names, 525 | struct_names, 526 | &fields, 527 | opts.meta_variants.is_some(), 528 | ); 529 | 530 | TokenStream::from_iter(output_items) 531 | } 532 | 533 | #[allow(clippy::too_many_arguments)] 534 | fn generate_wrapper_enums( 535 | type_name: &Ident, 536 | item: &ItemStruct, 537 | opts: &StructOpts, 538 | output_items: &mut Vec, 539 | variant_names: &[Ident], 540 | struct_names: &[Ident], 541 | fields: &[FieldData], 542 | is_meta: bool, 543 | ) { 544 | let visibility = &item.vis; 545 | // Extract the generics to use for the top-level type and all variant structs. 546 | let decl_generics = &item.generics; 547 | // Generics used for the impl block. 548 | let (impl_generics, ty_generics, where_clause) = &item.generics.split_for_impl(); 549 | 550 | // Construct the top-level enum. 551 | let top_level_attrs = discard_superstruct_attrs(&item.attrs); 552 | let enum_item = quote! { 553 | #( 554 | #top_level_attrs 555 | )* 556 | #visibility enum #type_name #decl_generics #where_clause { 557 | #( 558 | #variant_names(#struct_names #ty_generics), 559 | )* 560 | } 561 | }; 562 | output_items.push(enum_item.into()); 563 | 564 | // Construct a top-level reference type. 565 | // TODO: check that variants aren't called `Ref` 566 | let ref_ty_name = format_ident!("{}Ref", type_name); 567 | let ref_ty_lifetime = Lifetime::new("'__superstruct", Span::call_site()); 568 | 569 | // Muahaha, this is dank. 570 | // Inject the generated lifetime into the top-level type's generics. 571 | let mut ref_ty_decl_generics = decl_generics.clone(); 572 | ref_ty_decl_generics.params.insert( 573 | 0, 574 | GenericParam::Lifetime(LifetimeParam::new(ref_ty_lifetime.clone())), 575 | ); 576 | 577 | // If no lifetime bound exists for a generic param, inject one. 578 | for param in ref_ty_decl_generics.params.iter_mut() { 579 | if let GenericParam::Type(type_param) = param { 580 | let result = type_param 581 | .bounds 582 | .iter() 583 | .find(|bound| matches!(bound, TypeParamBound::Lifetime(_))); 584 | if result.is_none() { 585 | type_param 586 | .bounds 587 | .insert(0, TypeParamBound::Lifetime(ref_ty_lifetime.clone())) 588 | } 589 | } 590 | } 591 | 592 | let (ref_impl_generics, ref_ty_generics, _) = &ref_ty_decl_generics.split_for_impl(); 593 | 594 | // Prepare the attributes for the ref type. 595 | let ref_attributes = opts 596 | .ref_attributes 597 | .as_ref() 598 | .map_or(&[][..], |attrs| &attrs.metas); 599 | 600 | let ref_ty = quote! { 601 | #( 602 | #[#ref_attributes] 603 | )* 604 | #visibility enum #ref_ty_name #ref_ty_decl_generics #where_clause { 605 | #( 606 | #variant_names(&#ref_ty_lifetime #struct_names #ty_generics), 607 | )* 608 | } 609 | }; 610 | output_items.push(ref_ty.into()); 611 | 612 | // Construct a top-level mutable reference type. 613 | // TODO: check that variants aren't called `RefMut` 614 | let ref_mut_ty_name = format_ident!("{}RefMut", type_name); 615 | let ref_mut_ty_lifetime = Lifetime::new("'__superstruct", Span::call_site()); 616 | // Muahaha, this is dank. 617 | // Inject the generated lifetime into the top-level type's generics. 618 | let mut ref_mut_ty_decl_generics = decl_generics.clone(); 619 | ref_mut_ty_decl_generics.params.insert( 620 | 0, 621 | GenericParam::Lifetime(LifetimeParam::new(ref_mut_ty_lifetime.clone())), 622 | ); 623 | let (ref_mut_impl_generics, ref_mut_ty_generics, _) = 624 | &ref_mut_ty_decl_generics.split_for_impl(); 625 | 626 | // Prepare the attributes for the ref type. 627 | let ref_mut_attributes = opts 628 | .ref_mut_attributes 629 | .as_ref() 630 | .map_or(&[][..], |attrs| &attrs.metas); 631 | 632 | let ref_mut_ty = quote! { 633 | #( 634 | #[#ref_mut_attributes] 635 | )* 636 | #visibility enum #ref_mut_ty_name #ref_mut_ty_decl_generics #where_clause { 637 | #( 638 | #variant_names(&#ref_mut_ty_lifetime mut #struct_names #ty_generics), 639 | )* 640 | } 641 | }; 642 | output_items.push(ref_mut_ty.into()); 643 | 644 | // Construct the main impl block. 645 | let getters = fields 646 | .iter() 647 | .filter(|f| f.is_common() && !f.no_getter()) 648 | .map(|field_data| make_field_getter(type_name, variant_names, field_data, None, is_meta)); 649 | 650 | let mut_getters = fields 651 | .iter() 652 | .filter(|f| f.is_common() && !f.no_getter() && !f.getter_opts.no_mut) 653 | .map(|field_data| { 654 | make_mut_field_getter(type_name, variant_names, field_data, None, is_meta) 655 | }); 656 | 657 | let partial_getters = fields 658 | .iter() 659 | .filter(|f| !f.is_common() && !f.no_getter()) 660 | .filter(|f| is_meta || f.exists_in_meta(type_name)) 661 | .cartesian_product(&[false, true]) 662 | .flat_map(|(field_data, mutability)| { 663 | let field_variants = &field_data.only_combinations; 664 | Some(make_partial_getter( 665 | type_name, 666 | field_data, 667 | field_variants, 668 | &opts.partial_getter_error, 669 | *mutability, 670 | None, 671 | is_meta, 672 | )) 673 | }); 674 | 675 | let cast_methods = variant_names 676 | .iter() 677 | .flat_map(|variant_name| { 678 | let caster = make_as_variant_method( 679 | type_name, 680 | variant_name, 681 | ty_generics, 682 | &opts.cast_error, 683 | false, 684 | ); 685 | let caster_mut = make_as_variant_method( 686 | type_name, 687 | variant_name, 688 | ty_generics, 689 | &opts.cast_error, 690 | true, 691 | ); 692 | vec![caster, caster_mut] 693 | }) 694 | .collect_vec(); 695 | 696 | let impl_block = quote! { 697 | impl #impl_generics #type_name #ty_generics #where_clause { 698 | pub fn to_ref<#ref_ty_lifetime>(&#ref_ty_lifetime self) -> #ref_ty_name #ref_ty_generics { 699 | match self { 700 | #( 701 | #type_name::#variant_names(ref inner) 702 | => #ref_ty_name::#variant_names(inner), 703 | )* 704 | } 705 | } 706 | pub fn to_mut<#ref_mut_ty_lifetime>(&#ref_mut_ty_lifetime mut self) -> #ref_mut_ty_name #ref_mut_ty_generics { 707 | match self { 708 | #( 709 | #type_name::#variant_names(ref mut inner) 710 | => #ref_mut_ty_name::#variant_names(inner), 711 | )* 712 | } 713 | } 714 | #( 715 | #cast_methods 716 | )* 717 | #( 718 | #getters 719 | )* 720 | #( 721 | #mut_getters 722 | )* 723 | #( 724 | #partial_getters 725 | )* 726 | } 727 | }; 728 | output_items.push(impl_block.into()); 729 | 730 | // Construct the impl block for the *Ref type. 731 | let ref_getters = fields 732 | .iter() 733 | .filter(|f| f.is_common() && !f.no_getter()) 734 | .map(|field_data| { 735 | make_field_getter( 736 | &ref_ty_name, 737 | variant_names, 738 | field_data, 739 | Some(&ref_ty_lifetime), 740 | is_meta, 741 | ) 742 | }); 743 | 744 | let ref_partial_getters = fields 745 | .iter() 746 | .filter(|f| !f.is_common() && !f.no_getter()) 747 | .filter(|f| is_meta || f.exists_in_meta(type_name)) 748 | .flat_map(|field_data| { 749 | let field_variants = &field_data.only_combinations; 750 | Some(make_partial_getter( 751 | &ref_ty_name, 752 | field_data, 753 | field_variants, 754 | &opts.partial_getter_error, 755 | false, 756 | Some(&ref_ty_lifetime), 757 | is_meta, 758 | )) 759 | }); 760 | 761 | let ref_impl_block = quote! { 762 | impl #ref_impl_generics #ref_ty_name #ref_ty_generics #where_clause { 763 | #( 764 | #ref_getters 765 | )* 766 | 767 | #( 768 | #ref_partial_getters 769 | )* 770 | } 771 | 772 | // Reference types are just wrappers around references, so they can be copied! 773 | impl #ref_impl_generics Copy for #ref_ty_name #ref_ty_generics #where_clause { } 774 | impl #ref_impl_generics Clone for #ref_ty_name #ref_ty_generics #where_clause { 775 | fn clone(&self) -> Self { *self } 776 | } 777 | }; 778 | output_items.push(ref_impl_block.into()); 779 | 780 | // Construct the impl block for the *RefMut type. 781 | let ref_mut_getters = fields 782 | .iter() 783 | .filter(|f| f.is_common() && !f.no_getter() && !f.getter_opts.no_mut) 784 | .map(|field_data| { 785 | make_mut_field_getter( 786 | &ref_mut_ty_name, 787 | variant_names, 788 | field_data, 789 | Some(&ref_mut_ty_lifetime), 790 | is_meta, 791 | ) 792 | }); 793 | 794 | let ref_mut_partial_getters = fields 795 | .iter() 796 | .filter(|f| !f.is_common() && !f.no_getter() && !f.partial_getter_opts.no_mut) 797 | .filter(|f| is_meta || f.exists_in_meta(type_name)) 798 | .flat_map(|field_data| { 799 | let field_variants = &field_data.only_combinations; 800 | Some(make_partial_getter( 801 | &ref_mut_ty_name, 802 | field_data, 803 | field_variants, 804 | &opts.partial_getter_error, 805 | true, 806 | Some(&ref_mut_ty_lifetime), 807 | is_meta, 808 | )) 809 | }); 810 | 811 | let ref_mut_impl_block = quote! { 812 | impl #ref_mut_impl_generics #ref_mut_ty_name #ref_mut_ty_generics #where_clause { 813 | #( 814 | #ref_mut_getters 815 | )* 816 | 817 | #( 818 | #ref_mut_partial_getters 819 | )* 820 | } 821 | }; 822 | output_items.push(ref_mut_impl_block.into()); 823 | 824 | // Generate the mapping macros if enabled. 825 | if !opts.no_map_macros && !opts.no_enum { 826 | let num_generics = decl_generics.params.len(); 827 | generate_all_map_macros( 828 | type_name, 829 | &ref_ty_name, 830 | &ref_mut_ty_name, 831 | num_generics, 832 | struct_names, 833 | variant_names, 834 | opts, 835 | output_items, 836 | ); 837 | } else { 838 | assert!( 839 | opts.map_into.is_none(), 840 | "`map_into` is set but map macros are disabled" 841 | ); 842 | assert!( 843 | opts.map_ref_into.is_none(), 844 | "`map_ref_into` is set but map macros are disabled" 845 | ); 846 | assert!( 847 | opts.map_ref_mut_into.is_none(), 848 | "`map_ref_mut_into` is set but map macros are disabled" 849 | ); 850 | } 851 | 852 | // Generate trait implementations. 853 | for (variant_name, struct_name) in variant_names.iter().zip_eq(struct_names) { 854 | let from_impl = generate_from_variant_trait_impl( 855 | type_name, 856 | impl_generics, 857 | ty_generics, 858 | where_clause, 859 | variant_name, 860 | struct_name, 861 | ); 862 | output_items.push(from_impl.into()); 863 | 864 | let from_impl_for_ref = generate_from_variant_trait_impl_for_ref( 865 | &ref_ty_name, 866 | &ref_ty_lifetime, 867 | ref_impl_generics, 868 | ref_ty_generics, 869 | ty_generics, 870 | where_clause, 871 | variant_name, 872 | struct_name, 873 | ); 874 | output_items.push(from_impl_for_ref.into()); 875 | } 876 | 877 | // Convert reference to top-level type to `Ref`. 878 | let ref_from_top_level_impl = generate_from_enum_trait_impl_for_ref( 879 | type_name, 880 | ty_generics, 881 | &ref_ty_name, 882 | &ref_ty_lifetime, 883 | ref_impl_generics, 884 | ref_ty_generics, 885 | where_clause, 886 | ); 887 | output_items.push(ref_from_top_level_impl.into()); 888 | } 889 | 890 | /// Generate a getter method for a field. 891 | fn make_field_getter( 892 | type_name: &Ident, 893 | variant_names: &[Ident], 894 | field_data: &FieldData, 895 | lifetime: Option<&Lifetime>, 896 | is_meta: bool, 897 | ) -> proc_macro2::TokenStream { 898 | let field_name = &field_data.name; 899 | let field_type = &field_data.field.ty; 900 | let getter_opts = &field_data.getter_opts; 901 | 902 | let fn_name = getter_opts.rename.as_ref().unwrap_or(field_name); 903 | let return_type = if getter_opts.copy { 904 | quote! { #field_type } 905 | } else { 906 | quote! { &#lifetime #field_type} 907 | }; 908 | 909 | let return_expr = if is_meta { 910 | quote! { inner.#field_name() } 911 | } else if getter_opts.copy { 912 | quote! { inner.#field_name } 913 | } else { 914 | quote! { &inner.#field_name } 915 | }; 916 | 917 | // Pass-through `cfg` attributes as they affect the existence of this field. 918 | let cfg_attrs = get_cfg_attrs(&field_data.field.attrs); 919 | 920 | quote! { 921 | #( 922 | #cfg_attrs 923 | )* 924 | pub fn #fn_name(&self) -> #return_type { 925 | match self { 926 | #( 927 | #type_name::#variant_names(ref inner) => { 928 | #return_expr 929 | } 930 | )* 931 | } 932 | } 933 | } 934 | } 935 | 936 | /// Generate a mutable getter method for a field. 937 | fn make_mut_field_getter( 938 | type_name: &Ident, 939 | variant_names: &[Ident], 940 | field_data: &FieldData, 941 | lifetime: Option<&Lifetime>, 942 | is_meta: bool, 943 | ) -> proc_macro2::TokenStream { 944 | let field_name = &field_data.name; 945 | let field_type = &field_data.field.ty; 946 | let getter_opts = &field_data.getter_opts; 947 | 948 | let fn_name = format_ident!("{}_mut", getter_opts.rename.as_ref().unwrap_or(field_name)); 949 | let return_type = quote! { &#lifetime mut #field_type }; 950 | let param = make_self_arg(true, lifetime); 951 | let return_expr = if is_meta { 952 | quote! { inner.#fn_name() } 953 | } else { 954 | quote! { &mut inner.#field_name } 955 | }; 956 | 957 | // Pass-through `cfg` attributes as they affect the existence of this field. 958 | let cfg_attrs = get_cfg_attrs(&field_data.field.attrs); 959 | 960 | quote! { 961 | #( 962 | #cfg_attrs 963 | )* 964 | pub fn #fn_name(#param) -> #return_type { 965 | match self { 966 | #( 967 | #type_name::#variant_names(ref mut inner) => { 968 | #return_expr 969 | } 970 | )* 971 | } 972 | } 973 | } 974 | } 975 | 976 | fn make_self_arg(mutable: bool, lifetime: Option<&Lifetime>) -> proc_macro2::TokenStream { 977 | if mutable { 978 | quote! { &#lifetime mut self } 979 | } else { 980 | // Ignore the lifetime for immutable references. This allows `&Ref<'a>` to be de-referenced 981 | // to an inner pointer with lifetime `'a`. 982 | quote! { &self } 983 | } 984 | } 985 | 986 | fn make_type_ref( 987 | ty: &Type, 988 | mutable: bool, 989 | copy: bool, 990 | lifetime: Option<&Lifetime>, 991 | ) -> proc_macro2::TokenStream { 992 | // XXX: bit hacky, ignore `copy` if `mutable` is set 993 | if mutable { 994 | quote! { &#lifetime mut #ty } 995 | } else if copy { 996 | quote! { #ty } 997 | } else { 998 | quote! { &#lifetime #ty } 999 | } 1000 | } 1001 | 1002 | /// Generate a partial getter method for a field. 1003 | fn make_partial_getter( 1004 | type_name: &Ident, 1005 | field_data: &FieldData, 1006 | field_variants: &[VariantKey], 1007 | error_opts: &ErrorOpts, 1008 | mutable: bool, 1009 | lifetime: Option<&Lifetime>, 1010 | is_meta: bool, 1011 | ) -> proc_macro2::TokenStream { 1012 | let field_variants = field_variants 1013 | .iter() 1014 | .filter_map(|key| { 1015 | if is_meta { 1016 | key.meta_variant.clone() 1017 | } else { 1018 | Some(key.variant.clone()) 1019 | } 1020 | }) 1021 | .unique() 1022 | .collect_vec(); 1023 | let type_name = type_name.clone(); 1024 | 1025 | let field_name = &field_data.name; 1026 | let renamed_field = field_data 1027 | .partial_getter_opts 1028 | .rename 1029 | .as_ref() 1030 | .unwrap_or(field_name); 1031 | let fn_name = if mutable { 1032 | format_ident!("{}_mut", renamed_field) 1033 | } else { 1034 | renamed_field.clone() 1035 | }; 1036 | let copy = field_data.partial_getter_opts.copy; 1037 | let self_arg = make_self_arg(mutable, lifetime); 1038 | let ret_ty = make_type_ref(&field_data.field.ty, mutable, copy, lifetime); 1039 | let ret_expr = if is_meta { 1040 | quote! { inner.#fn_name()? } 1041 | } else if mutable { 1042 | quote! { &mut inner.#field_name } 1043 | } else if copy { 1044 | quote! { inner.#field_name } 1045 | } else { 1046 | quote! { &inner.#field_name } 1047 | }; 1048 | let (res_ret_ty, err_expr) = error_opts.build_result_type(&ret_ty); 1049 | 1050 | // Pass-through `cfg` attributes as they affect the existence of this field. 1051 | let cfg_attrs = get_cfg_attrs(&field_data.field.attrs); 1052 | 1053 | quote! { 1054 | #( 1055 | #cfg_attrs 1056 | )* 1057 | pub fn #fn_name(#self_arg) -> #res_ret_ty { 1058 | match self { 1059 | #( 1060 | #type_name::#field_variants(inner) => Ok(#ret_expr), 1061 | )* 1062 | _ => Err(#err_expr), 1063 | } 1064 | } 1065 | } 1066 | } 1067 | 1068 | /// Generate a `as_{_mut}` method. 1069 | fn make_as_variant_method( 1070 | type_name: &Ident, 1071 | variant_name: &Ident, 1072 | type_generics: &TypeGenerics, 1073 | cast_err_opts: &ErrorOpts, 1074 | mutable: bool, 1075 | ) -> proc_macro2::TokenStream { 1076 | let variant_ty = format_ident!("{}{}", type_name, variant_name); 1077 | let (suffix, arg, ret_ty, binding) = if mutable { 1078 | ( 1079 | "_mut", 1080 | quote! { &mut self }, 1081 | quote! { &mut #variant_ty #type_generics }, 1082 | quote! { ref mut inner }, 1083 | ) 1084 | } else { 1085 | ( 1086 | "", 1087 | quote! { &self }, 1088 | quote! { &#variant_ty #type_generics }, 1089 | quote! { ref inner }, 1090 | ) 1091 | }; 1092 | let (ret_res_ty, err_expr) = cast_err_opts.build_result_type(&ret_ty); 1093 | let fn_name = format_ident!("as_{}{}", variant_name.to_string().to_lowercase(), suffix); 1094 | quote! { 1095 | pub fn #fn_name(#arg) -> #ret_res_ty { 1096 | match self { 1097 | #type_name::#variant_name(#binding) => Ok(inner), 1098 | _ => Err(#err_expr), 1099 | } 1100 | } 1101 | } 1102 | } 1103 | 1104 | /// Check that there is at most one superstruct attribute, and panic otherwise. 1105 | fn check_for_conflicting_superstruct_attrs(attrs: &[Attribute]) { 1106 | if attrs 1107 | .iter() 1108 | .filter(|attr| is_superstruct_attr(attr)) 1109 | .count() 1110 | > 1 1111 | { 1112 | // TODO: this is specific to fields right now, but we could maybe make it work for the 1113 | // top-level attributes. I'm just not sure how to get at them under the `AttributeArgs` 1114 | // stuff. 1115 | panic!("cannot handle more than one superstruct attribute per field"); 1116 | } 1117 | } 1118 | 1119 | /// Keep all non-superstruct-related attributes from an array. 1120 | fn discard_superstruct_attrs(attrs: &[Attribute]) -> Vec { 1121 | attrs 1122 | .iter() 1123 | .filter(|attr| !is_superstruct_attr(attr)) 1124 | .cloned() 1125 | .collect() 1126 | } 1127 | 1128 | /// Keep only `cfg` attributes from an array. 1129 | fn get_cfg_attrs(attrs: &[Attribute]) -> Vec { 1130 | attrs 1131 | .iter() 1132 | .filter(|attr| is_attr_with_ident(attr, "cfg")) 1133 | .cloned() 1134 | .collect() 1135 | } 1136 | 1137 | /// Predicate for determining whether an attribute is a `superstruct` attribute. 1138 | fn is_superstruct_attr(attr: &Attribute) -> bool { 1139 | is_attr_with_ident(attr, "superstruct") 1140 | } 1141 | 1142 | /// Predicate for determining whether an attribute has the given `ident` as its path. 1143 | fn is_attr_with_ident(attr: &Attribute, ident: &str) -> bool { 1144 | attr.path() 1145 | .get_ident() 1146 | .is_some_and(|attr_ident| *attr_ident == ident) 1147 | } 1148 | 1149 | /// Predicate for determining whether a field should be excluded from a flattened 1150 | /// variant combination. 1151 | fn should_skip( 1152 | variant_names: &[Ident], 1153 | meta_variant_names: &[Option], 1154 | flatten: &Override>, 1155 | variant_key: &VariantKey, 1156 | ) -> bool { 1157 | let variant = &variant_key.variant; 1158 | let meta_variant = variant_key.meta_variant.as_ref(); 1159 | match flatten { 1160 | Override::Inherit => false, 1161 | Override::Explicit(map) => { 1162 | let contains_variant = map.contains_key(variant); 1163 | let contains_meta_variant = meta_variant.is_none_or(|mv| map.contains_key(mv)); 1164 | 1165 | let variants_exist = variant_names.iter().any(|v| map.contains_key(v)); 1166 | let meta_variants_exist = meta_variant_names 1167 | .iter() 1168 | .flatten() 1169 | .any(|mv| map.contains_key(mv)); 1170 | 1171 | if contains_variant && !meta_variants_exist { 1172 | return false; 1173 | } 1174 | if contains_meta_variant && !variants_exist { 1175 | return false; 1176 | } 1177 | 1178 | let contains_all = contains_variant && contains_meta_variant; 1179 | 1180 | !map.is_empty() && !contains_all 1181 | } 1182 | } 1183 | } 1184 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | use crate::attributes::IdentList; 2 | use crate::naming::generate_map_macro_name; 3 | use crate::utils::underscore_generics; 4 | use crate::{StructOpts, TokenStream, TokenStream2}; 5 | use quote::quote; 6 | use syn::Ident; 7 | 8 | pub struct MacroFromType<'a> { 9 | /// The name of the superstruct type being matched on. 10 | pub name: &'a Ident, 11 | /// The number of generic type parameters. 12 | pub num_generics: usize, 13 | /// The names of the variant structs. 14 | pub struct_names: &'a [Ident], 15 | } 16 | 17 | /// Generate all the map macros for the top-level enum, Ref and RefMut. 18 | #[allow(clippy::too_many_arguments)] 19 | pub(crate) fn generate_all_map_macros( 20 | type_name: &Ident, 21 | ref_type_name: &Ident, 22 | ref_mut_type_name: &Ident, 23 | num_generics: usize, 24 | struct_names: &[Ident], 25 | variant_names: &[Ident], 26 | opts: &StructOpts, 27 | output_items: &mut Vec, 28 | ) { 29 | generate_all_map_macros_for_type( 30 | type_name, 31 | num_generics, 32 | struct_names, 33 | &opts.map_into, 34 | |from_type, to_type| generate_owned_map_macro(from_type, to_type, variant_names), 35 | output_items, 36 | ); 37 | 38 | generate_all_map_macros_for_type( 39 | ref_type_name, 40 | num_generics, 41 | struct_names, 42 | &opts.map_ref_into, 43 | |from_type, to_type| generate_ref_map_macro(from_type, to_type, variant_names, false), 44 | output_items, 45 | ); 46 | 47 | generate_all_map_macros_for_type( 48 | ref_mut_type_name, 49 | num_generics, 50 | struct_names, 51 | &opts.map_ref_mut_into, 52 | |from_type, to_type| generate_ref_map_macro(from_type, to_type, variant_names, true), 53 | output_items, 54 | ); 55 | } 56 | 57 | fn generate_all_map_macros_for_type( 58 | type_name: &Ident, 59 | num_generics: usize, 60 | struct_names: &[Ident], 61 | map_into: &Option, 62 | generator: impl Fn(&MacroFromType, Option<&Ident>) -> TokenStream2, 63 | output_items: &mut Vec, 64 | ) { 65 | let from_type = MacroFromType { 66 | name: type_name, 67 | num_generics, 68 | struct_names, 69 | }; 70 | let map_macro_self = generator(&from_type, None); 71 | output_items.push(map_macro_self.into()); 72 | 73 | if let Some(map_into) = map_into { 74 | for to_type in &map_into.idents { 75 | let map_macro_to = generator(&from_type, Some(to_type)); 76 | output_items.push(map_macro_to.into()); 77 | } 78 | } 79 | } 80 | 81 | fn generate_owned_map_macro( 82 | from_type: &MacroFromType, 83 | to_type_name: Option<&Ident>, 84 | variant_names: &[Ident], 85 | ) -> TokenStream2 { 86 | assert_eq!( 87 | from_type.struct_names.len(), 88 | variant_names.len(), 89 | "there must be one struct per variant" 90 | ); 91 | 92 | let from_type_name = &from_type.name; 93 | let from_type_struct_names = from_type.struct_names; 94 | let to_type_name = to_type_name.unwrap_or(from_type_name); 95 | let map_macro_name = generate_map_macro_name(from_type_name, to_type_name); 96 | 97 | // Generics we want the compiler to infer. 98 | let from_type_generics = underscore_generics(from_type.num_generics); 99 | 100 | quote! { 101 | #[macro_export] 102 | macro_rules! #map_macro_name { 103 | ($value:expr, $f:expr) => { 104 | match $value { 105 | #( 106 | #from_type_name::#variant_names(inner) => { 107 | let f: fn( 108 | #from_type_struct_names #from_type_generics, 109 | fn(_) -> _, 110 | ) -> _ = $f; 111 | f(inner, #to_type_name::#variant_names) 112 | } 113 | )* 114 | } 115 | } 116 | } 117 | } 118 | } 119 | 120 | fn generate_ref_map_macro( 121 | from_type: &MacroFromType, 122 | to_type_name: Option<&Ident>, 123 | variant_names: &[Ident], 124 | mutable: bool, 125 | ) -> TokenStream2 { 126 | assert_eq!( 127 | from_type.struct_names.len(), 128 | variant_names.len(), 129 | "there must be one struct per variant" 130 | ); 131 | 132 | let from_type_name = &from_type.name; 133 | let from_type_struct_names = from_type.struct_names; 134 | let to_type_name = to_type_name.unwrap_or(from_type_name); 135 | let map_macro_name = generate_map_macro_name(from_type_name, to_type_name); 136 | 137 | // Generics we want the compiler to infer. 138 | let from_type_generics = underscore_generics(from_type.num_generics); 139 | 140 | let mutability = if mutable { 141 | quote! { mut } 142 | } else { 143 | quote! {} 144 | }; 145 | 146 | quote! { 147 | #[macro_export] 148 | macro_rules! #map_macro_name { 149 | (&$lifetime:tt _, $value:expr, $f:expr) => { 150 | match $value { 151 | #( 152 | #from_type_name::#variant_names(inner) => { 153 | let f: fn( 154 | &$lifetime #mutability #from_type_struct_names #from_type_generics, 155 | fn(_) -> _, 156 | ) -> _ = $f; 157 | f(inner, #to_type_name::#variant_names) 158 | } 159 | )* 160 | } 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/naming.rs: -------------------------------------------------------------------------------- 1 | use crate::utils::snake_case; 2 | use quote::format_ident; 3 | use syn::Ident; 4 | 5 | pub fn generate_map_macro_name(from_type_name: &Ident, to_type_name: &Ident) -> Ident { 6 | if from_type_name == to_type_name { 7 | format_ident!("map_{}", snake_case(&from_type_name.to_string())) 8 | } else { 9 | format_ident!( 10 | "map_{}_into_{}", 11 | snake_case(&from_type_name.to_string()), 12 | snake_case(&to_type_name.to_string()) 13 | ) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::Span; 2 | use quote::quote; 3 | use smallvec::{smallvec, SmallVec}; 4 | use syn::Token; 5 | 6 | /// Convert an identifier from CamelCase to snake_case. 7 | pub fn snake_case(ident: &str) -> String { 8 | ident 9 | .chars() 10 | .enumerate() 11 | .flat_map(|(i, c)| { 12 | let chars: SmallVec<[char; 2]> = if c.is_uppercase() { 13 | if i == 0 { 14 | c.to_lowercase().collect() 15 | } else { 16 | std::iter::once('_').chain(c.to_lowercase()).collect() 17 | } 18 | } else { 19 | smallvec![c] 20 | }; 21 | chars 22 | }) 23 | .collect() 24 | } 25 | 26 | /// Create a generics block like `<_, _, _>` with `num_generics` underscores. 27 | pub fn underscore_generics(num_generics: usize) -> proc_macro2::TokenStream { 28 | let underscore = Token![_](Span::call_site()); 29 | let underscores = std::iter::repeat_n(quote! { #underscore }, num_generics); 30 | quote! { <#(#underscores),*> } 31 | } 32 | 33 | #[cfg(test)] 34 | mod test { 35 | use super::*; 36 | 37 | #[test] 38 | fn snake_case_correct() { 39 | assert_eq!(snake_case("BeaconBlock"), "beacon_block"); 40 | assert_eq!(snake_case("SignedBeaconBlock"), "signed_beacon_block"); 41 | assert_eq!(snake_case("StoreDHT"), "store_d_h_t"); // may want to change this in future 42 | assert_eq!(snake_case("hello_world"), "hello_world"); 43 | assert_eq!(snake_case("__"), "__"); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/basic.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use serde::Deserialize; 4 | use superstruct::superstruct; 5 | 6 | #[test] 7 | fn basic() { 8 | #[superstruct( 9 | variants(Base, Ext), 10 | variant_attributes(derive(Debug, PartialEq, Clone)), 11 | cast_error(ty = "BlockError", expr = "BlockError::WrongVariant"), 12 | partial_getter_error(ty = "BlockError", expr = "BlockError::WrongVariant") 13 | )] 14 | #[derive(Debug, PartialEq, Clone)] 15 | pub struct Block { 16 | #[superstruct(getter(copy))] 17 | slot: u64, 18 | data: Vec, 19 | #[superstruct(only(Ext), partial_getter(copy))] 20 | description: &'static str, 21 | } 22 | 23 | #[derive(Debug, PartialEq)] 24 | pub enum BlockError { 25 | WrongVariant, 26 | } 27 | 28 | let base = BlockBase { 29 | slot: 10, 30 | data: vec![], 31 | }; 32 | let ext = BlockExt { 33 | slot: 11, 34 | data: vec![10], 35 | description: "oooeee look at this", 36 | }; 37 | 38 | let mut block1 = Block::Base(base.clone()); 39 | let mut block2 = Block::Ext(ext.clone()); 40 | 41 | // Test basic getters. 42 | assert_eq!(block1.slot(), 10); 43 | assert_eq!(block2.slot(), 11); 44 | 45 | // Check ref getters. 46 | let block1_ref = block1.to_ref(); 47 | assert_eq!(block1_ref.slot(), 10); 48 | 49 | // Check casting 50 | assert_eq!(block1.as_base(), Ok(&base)); 51 | assert_eq!(block1.as_ext(), Err(BlockError::WrongVariant)); 52 | assert_eq!(block2.as_ext(), Ok(&ext)); 53 | assert_eq!(block2.as_base(), Err(BlockError::WrongVariant)); 54 | 55 | // Check mutable reference mutators. 56 | let mut block_mut_ref = block1.to_mut(); 57 | *block_mut_ref.slot_mut() = 1000; 58 | assert_eq!(block1.slot(), 1000); 59 | *block1.slot_mut() = 1001; 60 | assert_eq!(block1.slot(), 1001); 61 | 62 | // Check partial getters. 63 | assert_eq!(block1.description(), Err(BlockError::WrongVariant)); 64 | assert_eq!(block2.description().unwrap(), ext.description); 65 | *block2.description_mut().unwrap() = "updated"; 66 | assert_eq!(block2.description().unwrap(), "updated"); 67 | } 68 | 69 | // Test that superstruct's enum ordering is based on the ordering in `variants(...)`. 70 | // This test fails with variant order (A, B) because A is a subset of B and we're not 71 | // using `serde(deny_unknown_fields)`. 72 | #[test] 73 | fn serde_deserialise_order() { 74 | #[superstruct( 75 | variants(B, A), 76 | variant_attributes(derive(Debug, Deserialize, PartialEq)) 77 | )] 78 | #[derive(Debug, Deserialize, PartialEq)] 79 | #[serde(untagged)] 80 | struct Message { 81 | common: String, 82 | #[superstruct(only(B))] 83 | exclusive: String, 84 | } 85 | 86 | let message_str = r#"{"common": "hello", "exclusive": "world"}"#; 87 | let message: Message = serde_json::from_str(message_str).unwrap(); 88 | 89 | let expected = Message::B(MessageB { 90 | common: "hello".into(), 91 | exclusive: "world".into(), 92 | }); 93 | 94 | assert_eq!(message, expected); 95 | } 96 | 97 | #[test] 98 | #[allow(clippy::non_minimal_cfg)] 99 | fn cfg_attribute() { 100 | // Use `all()` as true. 101 | #[superstruct(variants(A, B), no_map_macros)] 102 | struct Message { 103 | #[cfg(not(all()))] 104 | pub value: String, 105 | #[cfg(all())] 106 | pub value: u64, 107 | 108 | #[superstruct(only(B))] 109 | #[cfg(not(all()))] 110 | pub partial: String, 111 | // Repeating the `only` is somewhat annoying, but OK for now. 112 | #[superstruct(only(B))] 113 | #[cfg(all())] 114 | pub partial: u64, 115 | } 116 | 117 | let a = Message::A(MessageA { value: 10 }); 118 | assert_eq!(*a.value(), 10); 119 | 120 | let b = Message::B(MessageB { 121 | value: 10, 122 | partial: 5, 123 | }); 124 | assert_eq!(*b.partial().unwrap(), 5); 125 | } 126 | 127 | #[test] 128 | fn no_enum() { 129 | #[superstruct(variants(A, B), no_enum)] 130 | struct Message { 131 | #[superstruct(only(A))] 132 | pub x: u64, 133 | #[superstruct(only(B))] 134 | pub y: u64, 135 | } 136 | 137 | type Message = MessageA; 138 | 139 | let a: Message = Message { x: 0 }; 140 | let b: MessageB = MessageB { y: 0 }; 141 | assert_eq!(a.x, b.y); 142 | } 143 | 144 | #[test] 145 | #[allow(dead_code)] 146 | fn no_getter() { 147 | #[superstruct(variants(A, B))] 148 | struct NoGetter { 149 | #[superstruct(only(A), no_getter)] 150 | pub x: u64, 151 | #[superstruct(only(B), no_getter)] 152 | pub x: String, 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /tests/flatten.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | #[test] 6 | fn flatten() { 7 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Eq)))] 8 | #[derive(Debug, PartialEq, Eq)] 9 | struct InnerMessage { 10 | pub x: u64, 11 | #[superstruct(only(B))] 12 | pub y: u64, 13 | } 14 | 15 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Eq)))] 16 | #[derive(Debug, PartialEq, Eq)] 17 | struct Message { 18 | #[superstruct(flatten)] 19 | pub inner: InnerMessage, 20 | } 21 | 22 | let message_a = Message::A(MessageA { 23 | inner: InnerMessageA { x: 1 }, 24 | }); 25 | let message_b = Message::B(MessageB { 26 | inner: InnerMessageB { x: 3, y: 4 }, 27 | }); 28 | assert_eq!(message_a.inner_a().unwrap().x, 1); 29 | assert!(message_a.inner_b().is_err()); 30 | assert_eq!(message_b.inner_b().unwrap().x, 3); 31 | assert_eq!(message_b.inner_b().unwrap().y, 4); 32 | assert!(message_b.inner_a().is_err()); 33 | 34 | let message_a_ref = MessageRef::A(&MessageA { 35 | inner: InnerMessageA { x: 1 }, 36 | }); 37 | let message_b_ref = MessageRef::B(&MessageB { 38 | inner: InnerMessageB { x: 3, y: 4 }, 39 | }); 40 | assert_eq!(message_a_ref.inner_a().unwrap().x, 1); 41 | assert!(message_a_ref.inner_b().is_err()); 42 | assert_eq!(message_b_ref.inner_b().unwrap().x, 3); 43 | assert_eq!(message_b_ref.inner_b().unwrap().y, 4); 44 | assert!(message_b_ref.inner_a().is_err()); 45 | 46 | let mut inner_a = MessageA { 47 | inner: InnerMessageA { x: 1 }, 48 | }; 49 | let mut inner_b = MessageB { 50 | inner: InnerMessageB { x: 3, y: 4 }, 51 | }; 52 | 53 | // Re-initialize the struct to avoid borrow checker errors. 54 | let mut message_a_ref_mut = MessageRefMut::A(&mut inner_a); 55 | assert_eq!(message_a_ref_mut.inner_a_mut().map(|inner| inner.x), Ok(1)); 56 | let mut message_a_ref_mut = MessageRefMut::A(&mut inner_a); 57 | assert!(message_a_ref_mut.inner_b_mut().is_err()); 58 | let mut message_b_ref_mut = MessageRefMut::B(&mut inner_b); 59 | assert_eq!(message_b_ref_mut.inner_b_mut().unwrap().x, 3); 60 | let mut message_b_ref_mut = MessageRefMut::B(&mut inner_b); 61 | assert_eq!(message_b_ref_mut.inner_b_mut().unwrap().y, 4); 62 | let mut message_b_ref_mut = MessageRefMut::B(&mut inner_b); 63 | assert!(message_b_ref_mut.inner_a_mut().is_err()); 64 | } 65 | 66 | #[test] 67 | fn flatten_subset() { 68 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Eq)))] 69 | #[derive(Debug, PartialEq, Eq)] 70 | struct InnerMessageSubset { 71 | pub x: u64, 72 | #[superstruct(only(B))] 73 | pub y: u64, 74 | } 75 | 76 | #[superstruct(variants(A, B, C), variant_attributes(derive(Debug, PartialEq, Eq)))] 77 | #[derive(Debug, PartialEq, Eq)] 78 | struct MessageSubset { 79 | #[superstruct(flatten(A, B))] 80 | pub inner: InnerMessageSubset, 81 | } 82 | 83 | let message_a = MessageSubset::A(MessageSubsetA { 84 | inner: InnerMessageSubsetA { x: 1 }, 85 | }); 86 | let message_b = MessageSubset::B(MessageSubsetB { 87 | inner: InnerMessageSubsetB { x: 3, y: 4 }, 88 | }); 89 | let message_c = MessageSubset::C(MessageSubsetC {}); 90 | assert_eq!(message_a.inner_a().unwrap().x, 1); 91 | assert!(message_a.inner_b().is_err()); 92 | assert_eq!(message_b.inner_b().unwrap().x, 3); 93 | assert_eq!(message_b.inner_b().unwrap().y, 4); 94 | assert!(message_b.inner_a().is_err()); 95 | assert!(message_c.inner_a().is_err()); 96 | assert!(message_c.inner_b().is_err()); 97 | } 98 | 99 | #[test] 100 | fn flatten_not_first_field() { 101 | use test_mod::*; 102 | 103 | // Put this type in a submodule to test path parsing in `flatten`. 104 | pub mod test_mod { 105 | use superstruct::superstruct; 106 | 107 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Eq)))] 108 | #[derive(Debug, PartialEq, Eq)] 109 | pub struct InnerMessageTwo { 110 | pub x: u64, 111 | #[superstruct(only(B))] 112 | pub y: u64, 113 | } 114 | } 115 | 116 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Eq)))] 117 | #[derive(Debug, PartialEq, Eq)] 118 | struct MessageTwo { 119 | #[superstruct(only(A), partial_getter(copy))] 120 | pub other: u64, 121 | #[superstruct(flatten)] 122 | pub inner: test_mod::InnerMessageTwo, 123 | } 124 | 125 | let message_a = MessageTwo::A(MessageTwoA { 126 | other: 21, 127 | inner: InnerMessageTwoA { x: 1 }, 128 | }); 129 | let message_b = MessageTwo::B(MessageTwoB { 130 | inner: InnerMessageTwoB { x: 3, y: 4 }, 131 | }); 132 | assert_eq!(message_a.other().unwrap(), 21); 133 | assert_eq!(message_a.inner_a().unwrap().x, 1); 134 | assert!(message_a.inner_b().is_err()); 135 | assert_eq!(message_b.inner_b().unwrap().x, 3); 136 | assert_eq!(message_b.inner_b().unwrap().y, 4); 137 | assert!(message_b.inner_a().is_err()); 138 | 139 | let message_a_ref = MessageTwoRef::A(&MessageTwoA { 140 | other: 21, 141 | inner: InnerMessageTwoA { x: 1 }, 142 | }); 143 | let message_b_ref = MessageTwoRef::B(&MessageTwoB { 144 | inner: InnerMessageTwoB { x: 3, y: 4 }, 145 | }); 146 | assert_eq!(message_a.other().unwrap(), 21); 147 | assert_eq!(message_a_ref.inner_a().unwrap().x, 1); 148 | assert!(message_a_ref.inner_b().is_err()); 149 | assert_eq!(message_b_ref.inner_b().unwrap().x, 3); 150 | assert_eq!(message_b_ref.inner_b().unwrap().y, 4); 151 | assert!(message_b_ref.inner_a().is_err()); 152 | 153 | let mut inner_a = MessageTwoA { 154 | other: 21, 155 | inner: InnerMessageTwoA { x: 1 }, 156 | }; 157 | let mut inner_b = MessageTwoB { 158 | inner: InnerMessageTwoB { x: 3, y: 4 }, 159 | }; 160 | 161 | // Re-initialize the struct to avoid borrow checker errors. 162 | let mut message_a_ref_mut = MessageTwoRefMut::A(&mut inner_a); 163 | assert_eq!(message_a_ref_mut.inner_a_mut().map(|inner| inner.x), Ok(1)); 164 | let mut message_a_ref_mut = MessageTwoRefMut::A(&mut inner_a); 165 | assert!(message_a_ref_mut.inner_b_mut().is_err()); 166 | let mut message_b_ref_mut = MessageTwoRefMut::B(&mut inner_b); 167 | assert_eq!(message_b_ref_mut.inner_b_mut().unwrap().x, 3); 168 | let mut message_b_ref_mut = MessageTwoRefMut::B(&mut inner_b); 169 | assert_eq!(message_b_ref_mut.inner_b_mut().unwrap().y, 4); 170 | let mut message_b_ref_mut = MessageTwoRefMut::B(&mut inner_b); 171 | assert!(message_b_ref_mut.inner_a_mut().is_err()); 172 | } 173 | -------------------------------------------------------------------------------- /tests/from.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use std::fmt::Display; 4 | use superstruct::superstruct; 5 | 6 | #[superstruct( 7 | variants(Good, Bad), 8 | variant_attributes(derive(Debug, Clone, PartialEq)) 9 | )] 10 | #[derive(Debug, Clone, PartialEq)] 11 | pub struct Message { 12 | #[superstruct(getter(copy))] 13 | id: u64, 14 | #[superstruct(only(Good))] 15 | good: T, 16 | #[superstruct(only(Bad))] 17 | bad: T, 18 | } 19 | 20 | #[test] 21 | fn generic_from_variant() { 22 | let message_good_variant = MessageGood { 23 | id: 0, 24 | good: "hello", 25 | }; 26 | let message_bad_variant = MessageBad { 27 | id: 1, 28 | bad: "noooooo", 29 | }; 30 | 31 | let message_good = Message::from(message_good_variant); 32 | let message_bad = Message::from(message_bad_variant); 33 | 34 | assert_eq!(message_good.id(), 0); 35 | assert_eq!(*message_good.good().unwrap(), "hello"); 36 | 37 | assert_eq!(message_bad.id(), 1); 38 | assert_eq!(*message_bad.bad().unwrap(), "noooooo"); 39 | } 40 | 41 | #[test] 42 | fn generic_ref_from() { 43 | let message_good_variant = MessageGood { 44 | id: 0, 45 | good: "hello", 46 | }; 47 | let message_bad_variant = MessageBad { 48 | id: 1, 49 | bad: "noooooo", 50 | }; 51 | 52 | // Check Ref from reference to variant. 53 | let message_good_ref = MessageRef::from(&message_good_variant); 54 | let message_bad_ref = MessageRef::from(&message_bad_variant); 55 | 56 | assert_eq!(message_good_ref.id(), 0); 57 | assert_eq!(*message_good_ref.good().unwrap(), "hello"); 58 | 59 | assert_eq!(message_bad_ref.id(), 1); 60 | assert_eq!(*message_bad_ref.bad().unwrap(), "noooooo"); 61 | 62 | // Check Ref from reference to top-level enum. 63 | let message_good = Message::from(message_good_variant.clone()); 64 | let message_good_ref = MessageRef::from(&message_good); 65 | 66 | assert_eq!(message_good_ref.id(), 0); 67 | assert_eq!(*message_good_ref.good().unwrap(), "hello"); 68 | } 69 | -------------------------------------------------------------------------------- /tests/map_macro.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | #[test] 6 | fn map_macro_basic() { 7 | #[superstruct(variants(Base, Ext), variant_attributes(derive(Debug, PartialEq)))] 8 | #[derive(Debug, PartialEq)] 9 | pub struct Block { 10 | #[superstruct(getter(copy))] 11 | slot: u64, 12 | #[superstruct(only(Ext), partial_getter(copy))] 13 | description: &'static str, 14 | } 15 | 16 | fn increment_slot(block: Block) -> Block { 17 | map_block!(block, |mut inner, cons| { 18 | inner.slot += 1; 19 | cons(inner) 20 | }) 21 | } 22 | 23 | fn get_slot_via_ref<'a>(block_ref: BlockRef<'a>) -> u64 { 24 | map_block_ref!(&'a _, block_ref, |inner, _| { inner.slot }) 25 | } 26 | 27 | assert_eq!( 28 | increment_slot(Block::Base(BlockBase { slot: 10 })).slot(), 29 | get_slot_via_ref(Block::Base(BlockBase { slot: 11 }).to_ref()) 30 | ); 31 | assert_eq!( 32 | increment_slot(Block::Ext(BlockExt { 33 | slot: 0, 34 | description: "test" 35 | })), 36 | Block::Ext(BlockExt { 37 | slot: 1, 38 | description: "test" 39 | }) 40 | ); 41 | } 42 | 43 | #[test] 44 | fn map_macro_generic() { 45 | #[superstruct(variants(Base, Ext), variant_attributes(derive(Debug, PartialEq)))] 46 | #[derive(Debug, PartialEq)] 47 | pub struct Blob { 48 | slot: T, 49 | #[superstruct(only(Ext), partial_getter(copy))] 50 | description: &'static str, 51 | } 52 | 53 | impl From> for BlobBase { 54 | fn from(blob: BlobBase) -> Self { 55 | BlobBase { 56 | slot: blob.slot as u16, 57 | } 58 | } 59 | } 60 | 61 | impl From> for BlobExt { 62 | fn from(blob: BlobExt) -> Self { 63 | Self { 64 | slot: blob.slot as u16, 65 | description: blob.description, 66 | } 67 | } 68 | } 69 | 70 | impl From> for Blob { 71 | fn from(blob: Blob) -> Self { 72 | map_blob!(blob, |inner, cons| { cons(inner.into()) }) 73 | } 74 | } 75 | 76 | assert_eq!( 77 | Blob::Base(BlobBase { slot: 10u16 }), 78 | Blob::Base(BlobBase { slot: 10u8 }).into(), 79 | ); 80 | } 81 | 82 | #[test] 83 | fn map_into() { 84 | #[superstruct( 85 | variants(A, B), 86 | variant_attributes(derive(Debug, PartialEq, Clone)), 87 | map_into(Thing2), 88 | map_ref_into(Thing2Ref), 89 | map_ref_mut_into(Thing2RefMut) 90 | )] 91 | #[derive(Debug, PartialEq, Clone)] 92 | pub struct Thing1 { 93 | #[superstruct(only(A), partial_getter(rename = "thing2a"))] 94 | thing2: Thing2A, 95 | #[superstruct(only(B), partial_getter(rename = "thing2b"))] 96 | thing2: Thing2B, 97 | } 98 | 99 | #[superstruct(variants(A, B), variant_attributes(derive(Debug, PartialEq, Clone)))] 100 | #[derive(Debug, PartialEq, Clone)] 101 | pub struct Thing2 { 102 | x: u64, 103 | } 104 | 105 | fn thing1_to_thing2(thing1: Thing1) -> Thing2 { 106 | map_thing1_into_thing2!(thing1, |inner, cons| { cons(inner.thing2) }) 107 | } 108 | 109 | fn thing1_ref_to_thing2_ref<'a>(thing1: Thing1Ref<'a>) -> Thing2Ref<'a> { 110 | map_thing1_ref_into_thing2_ref!(&'a _, thing1, |inner, cons| { cons(&inner.thing2) }) 111 | } 112 | 113 | fn thing1_ref_mut_to_thing2_ref_mut<'a>(thing1: Thing1RefMut<'a>) -> Thing2RefMut<'a> { 114 | map_thing1_ref_mut_into_thing2_ref_mut!(&'a _, thing1, |inner, cons| { 115 | cons(&mut inner.thing2) 116 | }) 117 | } 118 | 119 | let thing2a = Thing2A { x: 10 }; 120 | let mut thing2 = Thing2::A(thing2a.clone()); 121 | let mut thing1 = Thing1::A(Thing1A { thing2: thing2a }); 122 | assert_eq!(thing1_to_thing2(thing1.clone()).x(), thing2.x()); 123 | assert_eq!( 124 | thing1_ref_to_thing2_ref(thing1.to_ref()).x(), 125 | thing2.to_ref().x() 126 | ); 127 | assert_eq!( 128 | thing1_ref_mut_to_thing2_ref_mut(thing1.to_mut()).x_mut(), 129 | thing2.to_mut().x_mut() 130 | ); 131 | 132 | // Mutatating through the Thing2RefMut should change the value. 133 | *thing1_ref_mut_to_thing2_ref_mut(thing1.to_mut()).x_mut() = 11; 134 | assert_eq!(*thing1_ref_to_thing2_ref(thing1.to_ref()).x(), 11); 135 | } 136 | -------------------------------------------------------------------------------- /tests/meta_variant.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | #[superstruct( 6 | meta_variants(Read, Write), 7 | variants(Lower, Upper), 8 | variant_attributes(derive(Clone, Debug, PartialEq, Eq)) 9 | )] 10 | #[derive(Clone, Debug, PartialEq, Eq)] 11 | struct InnerMessage { 12 | // Exists on all structs. 13 | pub w: u64, 14 | // Exists on all Read structs. 15 | #[superstruct(meta_only(Read))] 16 | pub x: u64, 17 | // Exists on all LowerCase structs. 18 | #[superstruct(only(Lower))] 19 | pub y: u64, 20 | // Exists only in InnerMessageWriteLower. 21 | #[superstruct(meta_only(Write), only(Upper))] 22 | pub z: u64, 23 | } 24 | 25 | #[test] 26 | fn meta_variant() { 27 | let message_a = InnerMessage::Read(InnerMessageRead::Lower(InnerMessageReadLower { 28 | w: 1, 29 | x: 2, 30 | y: 3, 31 | })); 32 | assert_eq!(*message_a.w(), 1); 33 | assert_eq!(*message_a.x().unwrap(), 2); 34 | assert_eq!(*message_a.y().unwrap(), 3); 35 | assert!(message_a.z().is_err()); 36 | 37 | let message_b = InnerMessage::Read(InnerMessageRead::Upper(InnerMessageReadUpper { 38 | w: 1, 39 | x: 2, 40 | })); 41 | assert_eq!(*message_b.w(), 1); 42 | assert_eq!(*message_b.x().unwrap(), 2); 43 | assert!(message_b.y().is_err()); 44 | assert!(message_b.z().is_err()); 45 | 46 | let message_c = InnerMessage::Write(InnerMessageWrite::Lower(InnerMessageWriteLower { 47 | w: 1, 48 | y: 3, 49 | })); 50 | assert_eq!(*message_c.w(), 1); 51 | assert!(message_c.x().is_err()); 52 | assert_eq!(*message_c.y().unwrap(), 3); 53 | assert!(message_c.z().is_err()); 54 | 55 | let message_d = InnerMessage::Write(InnerMessageWrite::Upper(InnerMessageWriteUpper { 56 | w: 1, 57 | z: 4, 58 | })); 59 | assert_eq!(*message_d.w(), 1); 60 | assert!(message_d.x().is_err()); 61 | assert!(message_d.y().is_err()); 62 | assert_eq!(*message_d.z().unwrap(), 4); 63 | } 64 | 65 | #[superstruct( 66 | meta_variants(Read, Write), 67 | variants(Lower, Upper), 68 | variant_attributes(derive(Debug, PartialEq, Eq)) 69 | )] 70 | #[derive(Debug, PartialEq, Eq)] 71 | struct Message { 72 | // Exists on all variants. 73 | #[superstruct(flatten)] 74 | pub inner_a: InnerMessage, 75 | // Exists on all Upper variants. 76 | #[superstruct(flatten(Upper))] 77 | pub inner_b: InnerMessage, 78 | // Exists on all Read variants. 79 | #[superstruct(flatten(Read))] 80 | pub inner_c: InnerMessage, 81 | // Exists on only the Read + Lower variant. 82 | #[superstruct(flatten(Write, Lower))] 83 | pub inner_d: InnerMessage, 84 | } 85 | 86 | #[test] 87 | fn meta_variant_flatten() { 88 | let inner_a = InnerMessageReadLower { w: 1, x: 2, y: 3 }; 89 | let inner_c = InnerMessageReadLower { w: 4, x: 5, y: 6 }; 90 | let message_e = Message::Read(MessageRead::Lower(MessageReadLower { inner_a, inner_c })); 91 | assert_eq!(message_e.inner_a_read_lower().unwrap().w, 1); 92 | assert!(message_e.inner_a_read_upper().is_err()); 93 | assert!(message_e.inner_a_write_lower().is_err()); 94 | assert!(message_e.inner_a_write_upper().is_err()); 95 | 96 | assert_eq!(message_e.inner_c_read_lower().unwrap().w, 4); 97 | assert!(message_e.inner_c_read_upper().is_err()); 98 | 99 | let inner_a = InnerMessageReadUpper { w: 1, x: 2 }; 100 | let inner_b = InnerMessageReadUpper { w: 3, x: 4 }; 101 | let inner_c = InnerMessageReadUpper { w: 5, x: 6 }; 102 | let message_f = Message::Read(MessageRead::Upper(MessageReadUpper { 103 | inner_a, 104 | inner_b, 105 | inner_c, 106 | })); 107 | assert!(message_f.inner_a_read_lower().is_err()); 108 | assert_eq!(message_f.inner_a_read_upper().unwrap().w, 1); 109 | assert!(message_f.inner_a_write_lower().is_err()); 110 | assert!(message_f.inner_a_write_upper().is_err()); 111 | 112 | assert_eq!(message_f.inner_b_read_upper().unwrap().w, 3); 113 | assert!(message_f.inner_b_write_upper().is_err()); 114 | 115 | assert!(message_f.inner_c_read_lower().is_err()); 116 | assert_eq!(message_f.inner_c_read_upper().unwrap().w, 5); 117 | 118 | let inner_a = InnerMessageWriteLower { w: 1, y: 2 }; 119 | let inner_d = InnerMessageWriteLower { w: 3, y: 4 }; 120 | let message_g = Message::Write(MessageWrite::Lower(MessageWriteLower { inner_a, inner_d })); 121 | assert!(message_g.inner_a_read_lower().is_err()); 122 | assert!(message_g.inner_a_read_upper().is_err()); 123 | assert_eq!(message_g.inner_a_write_lower().unwrap().w, 1); 124 | assert!(message_g.inner_a_write_upper().is_err()); 125 | 126 | assert_eq!(message_g.inner_d_write_lower().unwrap().w, 3); 127 | 128 | let inner_a = InnerMessageWriteUpper { w: 1, z: 2 }; 129 | let inner_b = InnerMessageWriteUpper { w: 3, z: 4 }; 130 | let message_h = Message::Write(MessageWrite::Upper(MessageWriteUpper { inner_a, inner_b })); 131 | assert!(message_h.inner_a_read_lower().is_err()); 132 | assert!(message_h.inner_a_read_upper().is_err()); 133 | assert!(message_h.inner_a_write_lower().is_err()); 134 | assert_eq!(message_h.inner_a_write_upper().unwrap().w, 1); 135 | 136 | assert!(message_h.inner_b_read_upper().is_err()); 137 | assert_eq!(message_h.inner_b_write_upper().unwrap().w, 3); 138 | } 139 | 140 | #[test] 141 | fn meta_variants_map_macro() { 142 | #[superstruct( 143 | meta_variants(Juicy, Sour), 144 | variants(Apple, Orange), 145 | variant_attributes(derive(Debug, PartialEq)) 146 | )] 147 | #[derive(Debug, PartialEq)] 148 | pub struct Fruit { 149 | #[superstruct(getter(copy))] 150 | id: u64, 151 | #[superstruct(only(Apple), partial_getter(copy))] 152 | description: &'static str, 153 | #[superstruct(meta_only(Juicy))] 154 | name: &'static str, 155 | } 156 | 157 | fn increment_id(id: Fruit) -> Fruit { 158 | map_fruit!(id, |mut inner, cons| { 159 | *inner.id_mut() += 1; 160 | cons(inner) 161 | }) 162 | } 163 | 164 | fn get_id_via_ref<'a>(fruit_ref: FruitRef<'a>) -> u64 { 165 | map_fruit_ref!(&'a _, fruit_ref, |inner, _| { inner.id() }) 166 | } 167 | 168 | assert_eq!( 169 | increment_id(Fruit::Juicy(FruitJuicy::Orange(FruitJuicyOrange { 170 | id: 10, 171 | name: "orange" 172 | }))) 173 | .id(), 174 | get_id_via_ref( 175 | Fruit::Juicy(FruitJuicy::Orange(FruitJuicyOrange { 176 | id: 11, 177 | name: "orange" 178 | })) 179 | .to_ref() 180 | ) 181 | ); 182 | } 183 | 184 | #[test] 185 | fn meta_variants_exist_specific_attributes() { 186 | #[superstruct( 187 | meta_variants(One, Two), 188 | variants(IsCopy, IsNotCopy), 189 | variant_attributes(derive(Debug, PartialEq, Clone)), 190 | specific_variant_attributes(IsCopy(derive(Copy))) 191 | )] 192 | #[derive(Clone, PartialEq, Debug)] 193 | pub struct Thing { 194 | pub x: u64, 195 | #[superstruct(only(IsNotCopy))] 196 | pub y: String, 197 | } 198 | 199 | fn copy(t: T) -> (T, T) { 200 | (t, t) 201 | } 202 | 203 | let x = ThingOneIsCopy { x: 0 }; 204 | assert_eq!(copy(x), (x, x)); 205 | let x = ThingTwoIsCopy { x: 0 }; 206 | assert_eq!(copy(x), (x, x)); 207 | } 208 | 209 | #[test] 210 | fn meta_variants_have_specific_attributes() { 211 | #[superstruct( 212 | meta_variants(IsCopy, IsNotCopy), 213 | variants(One, Two), 214 | variant_attributes(derive(Debug, PartialEq, Clone)), 215 | specific_variant_attributes(IsCopy(derive(Copy))) 216 | )] 217 | #[derive(Clone, PartialEq, Debug)] 218 | pub struct Ting { 219 | pub x: u64, 220 | #[superstruct(meta_only(IsNotCopy))] 221 | pub y: String, 222 | } 223 | 224 | fn copy(t: T) -> (T, T) { 225 | (t, t) 226 | } 227 | 228 | let x = TingIsCopyOne { x: 0 }; 229 | assert_eq!(copy(x), (x, x)); 230 | let x = TingIsCopyTwo { x: 0 }; 231 | assert_eq!(copy(x), (x, x)); 232 | } 233 | 234 | #[test] 235 | fn meta_only_flatten() { 236 | #[superstruct( 237 | variants(Merge, Capella), 238 | variant_attributes(derive(Debug, PartialEq, Clone)) 239 | )] 240 | #[derive(Clone, PartialEq, Debug)] 241 | pub struct Payload { 242 | pub transactions: u64, 243 | } 244 | 245 | #[superstruct( 246 | variants(Merge, Capella), 247 | variant_attributes(derive(Debug, PartialEq, Clone)) 248 | )] 249 | #[derive(Clone, PartialEq, Debug)] 250 | pub struct PayloadHeader { 251 | pub transactions_root: u64, 252 | } 253 | 254 | #[superstruct( 255 | meta_variants(Blinded, Full), 256 | variants(Base, Merge, Capella), 257 | variant_attributes(derive(Debug, PartialEq, Clone)) 258 | )] 259 | #[derive(Clone, PartialEq, Debug)] 260 | pub struct Block { 261 | #[superstruct(flatten(Merge, Capella), meta_only(Full))] 262 | pub payload: Payload, 263 | #[superstruct(flatten(Merge, Capella), meta_only(Blinded))] 264 | pub payload_header: PayloadHeader, 265 | } 266 | 267 | let block = Block::Full(BlockFull::Merge(BlockFullMerge { 268 | payload: PayloadMerge { transactions: 1 }, 269 | })); 270 | let blinded_block = Block::Blinded(BlockBlinded::Merge(BlockBlindedMerge { 271 | payload_header: PayloadHeaderMerge { 272 | transactions_root: 1, 273 | }, 274 | })); 275 | 276 | assert_eq!(block.payload_merge().unwrap().transactions, 1); 277 | assert_eq!( 278 | blinded_block 279 | .payload_header_merge() 280 | .unwrap() 281 | .transactions_root, 282 | 1 283 | ); 284 | } 285 | -------------------------------------------------------------------------------- /tests/ref.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | // Check that we can convert a Ref to an inner reference with the same lifetime as `message`. 6 | #[test] 7 | fn getter_and_partial_getter_lifetimes() { 8 | #[superstruct(variants(A, B))] 9 | struct Message { 10 | pub x: String, 11 | #[superstruct(only(B))] 12 | pub y: String, 13 | } 14 | 15 | fn get_x(message: &Message) -> &String { 16 | message.to_ref().x() 17 | } 18 | 19 | fn get_y(message: &Message) -> Result<&String, ()> { 20 | message.to_ref().y() 21 | } 22 | 23 | let m = Message::B(MessageB { 24 | x: "hello".into(), 25 | y: "world".into(), 26 | }); 27 | let x = get_x(&m); 28 | let y = get_y(&m).unwrap(); 29 | assert_eq!(x, "hello"); 30 | assert_eq!(y, "world"); 31 | } 32 | -------------------------------------------------------------------------------- /tests/ref_mut.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | #[test] 6 | fn partial_getter() { 7 | #[superstruct(variants(A, B))] 8 | struct Message { 9 | pub x: u64, 10 | #[superstruct(only(B))] 11 | pub y: u64, 12 | } 13 | 14 | let mut m = Message::B(MessageB { x: 0, y: 10 }); 15 | let mut mut_ref = m.to_mut(); 16 | *mut_ref.y_mut().unwrap() = 100; 17 | 18 | assert_eq!(*m.y().unwrap(), 100); 19 | assert_eq!(*m.x(), 0); 20 | } 21 | 22 | #[test] 23 | fn copy_partial_getter() { 24 | #[superstruct(variants(A, B), no_map_macros)] 25 | struct Message { 26 | #[superstruct(getter(copy))] 27 | pub x: u64, 28 | #[superstruct(only(B), partial_getter(copy))] 29 | pub y: u64, 30 | } 31 | 32 | let mut m = Message::B(MessageB { x: 0, y: 10 }); 33 | let mut mut_ref = m.to_mut(); 34 | *mut_ref.y_mut().unwrap() = 100; 35 | 36 | assert_eq!(m.y().unwrap(), 100); 37 | assert_eq!(m.x(), 0); 38 | } 39 | -------------------------------------------------------------------------------- /tests/specific_variant_attributes.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_local_definitions)] // for macros on structs within test functions 2 | 3 | use superstruct::superstruct; 4 | 5 | #[superstruct( 6 | variants(IsCopy, IsNotCopy), 7 | variant_attributes(derive(Debug, PartialEq, Clone)), 8 | specific_variant_attributes(IsCopy(derive(Copy))) 9 | )] 10 | #[derive(Clone, PartialEq, Debug)] 11 | pub struct Thing { 12 | pub x: u64, 13 | #[superstruct(only(IsNotCopy))] 14 | pub y: String, 15 | } 16 | 17 | #[test] 18 | fn copy_the_thing() { 19 | fn copy(t: T) -> (T, T) { 20 | (t, t) 21 | } 22 | 23 | let x = ThingIsCopy { x: 0 }; 24 | assert_eq!(copy(x), (x, x)); 25 | } 26 | --------------------------------------------------------------------------------