├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .rustfmt.toml ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── demo ├── Cargo.lock ├── Cargo.toml └── src │ └── main.rs ├── examples ├── bound-erasure-fn.rs ├── bound-erasure.rs ├── generics.rs ├── nesting.rs ├── raw-ident.rs ├── simple.rs └── syn.rs ├── images └── sealed.png ├── rust-toolchain ├── src └── lib.rs └── tests ├── fail ├── 01-general.rs ├── 01-general.stderr ├── 02-nesting.rs ├── 02-nesting.stderr ├── 03-private-by-default.rs ├── 03-private-by-default.stderr ├── 04-no-full-pub.rs ├── 04-no-full-pub.stderr ├── 05-no-comma.rs ├── 05-no-comma.stderr ├── 06-wrong-argument.rs └── 06-wrong-argument.stderr ├── pass ├── 01-long-name.rs ├── 02-nesting.rs ├── 03-generics.rs ├── 04-multiple-traits.rs ├── 05-raw-ident.rs ├── 06-bounds.rs ├── 07-bound-erasure.rs ├── 08-bound-erasure-fn.rs ├── 09-enum.rs ├── 10-all-arguments.rs ├── 11-where.rs ├── 12-lifetime.rs ├── 13-const-generics.rs └── 14-supertrait.rs └── test.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | 8 | jobs: 9 | tests: 10 | name: Rust 1.61.0 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: dtolnay/rust-toolchain@1.61.0 15 | - run: cargo test 16 | 17 | clippy: 18 | name: Clippy 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v4 22 | - uses: dtolnay/rust-toolchain@1.61.0 23 | with: 24 | components: clippy 25 | - run: cargo clippy -- --no-deps -Dclippy::all 26 | - run: cargo clippy --tests -- --no-deps -Dclippy::all 27 | - run: cargo clippy --examples -- --no-deps -Dclippy::all 28 | 29 | rustfmt: 30 | name: Rustfmt 31 | runs-on: ubuntu-latest 32 | steps: 33 | - uses: actions/checkout@v4 34 | - uses: dtolnay/rust-toolchain@1.61.0 35 | with: 36 | components: rustfmt 37 | - run: cargo fmt --all -- --check 38 | - run: rustfmt --check tests/**/*.rs 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # These are backup files generated by rustfmt 7 | **/*.rs.bk 8 | 9 | # MSVC Windows builds of rustc generate these, which store debugging information 10 | *.pdb 11 | 12 | .DS_Store 13 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false 2 | tab_spaces = 4 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to `sealed` 2 | 3 | - Ensure you're using Rust 1.61.0 to develop and test. 4 | This is required because we test macro error messages, which are not stable across 5 | compiler versions. Pinning the version everyone uses when developing `sealed` was the 6 | solution I found. If you know of a better solution, 7 | [let me know](https://github.com/jmg-duarte/sealed-rs/issues/new)! 8 | 9 | - If you're adding new functionality, add tests to the new functionality and existing 10 | ones, ensuring they all play nice with each other! 11 | 12 | - If you're fixing existing functionality, start by adding a minimal reproducible 13 | example as a test and fix the code until you achieve the desired behavior. 14 | 15 | Have fun! 16 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "basic-toml" 7 | version = "0.1.7" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "2f2139706359229bfa8f19142ac1155b4b80beafb7a60471ac5dd109d4a19778" 10 | dependencies = [ 11 | "serde", 12 | ] 13 | 14 | [[package]] 15 | name = "demo" 16 | version = "0.1.0" 17 | dependencies = [ 18 | "sealed", 19 | ] 20 | 21 | [[package]] 22 | name = "dissimilar" 23 | version = "1.0.7" 24 | source = "registry+https://github.com/rust-lang/crates.io-index" 25 | checksum = "86e3bdc80eee6e16b2b6b0f87fbc98c04bee3455e35174c0de1a125d0688c632" 26 | 27 | [[package]] 28 | name = "glob" 29 | version = "0.3.1" 30 | source = "registry+https://github.com/rust-lang/crates.io-index" 31 | checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" 32 | 33 | [[package]] 34 | name = "itoa" 35 | version = "1.0.10" 36 | source = "registry+https://github.com/rust-lang/crates.io-index" 37 | checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" 38 | 39 | [[package]] 40 | name = "once_cell" 41 | version = "1.17.2" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | checksum = "9670a07f94779e00908f3e686eab508878ebb390ba6e604d3a284c00e8d0487b" 44 | 45 | [[package]] 46 | name = "proc-macro2" 47 | version = "1.0.70" 48 | source = "registry+https://github.com/rust-lang/crates.io-index" 49 | checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" 50 | dependencies = [ 51 | "unicode-ident", 52 | ] 53 | 54 | [[package]] 55 | name = "quote" 56 | version = "1.0.33" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" 59 | dependencies = [ 60 | "proc-macro2", 61 | ] 62 | 63 | [[package]] 64 | name = "ryu" 65 | version = "1.0.16" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" 68 | 69 | [[package]] 70 | name = "sealed" 71 | version = "0.6.0" 72 | dependencies = [ 73 | "proc-macro2", 74 | "quote", 75 | "syn", 76 | "trybuild", 77 | ] 78 | 79 | [[package]] 80 | name = "serde" 81 | version = "1.0.193" 82 | source = "registry+https://github.com/rust-lang/crates.io-index" 83 | checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" 84 | dependencies = [ 85 | "serde_derive", 86 | ] 87 | 88 | [[package]] 89 | name = "serde_derive" 90 | version = "1.0.193" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" 93 | dependencies = [ 94 | "proc-macro2", 95 | "quote", 96 | "syn", 97 | ] 98 | 99 | [[package]] 100 | name = "serde_json" 101 | version = "1.0.108" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" 104 | dependencies = [ 105 | "itoa", 106 | "ryu", 107 | "serde", 108 | ] 109 | 110 | [[package]] 111 | name = "syn" 112 | version = "2.0.41" 113 | source = "registry+https://github.com/rust-lang/crates.io-index" 114 | checksum = "44c8b28c477cc3bf0e7966561e3460130e1255f7a1cf71931075f1c5e7a7e269" 115 | dependencies = [ 116 | "proc-macro2", 117 | "quote", 118 | "unicode-ident", 119 | ] 120 | 121 | [[package]] 122 | name = "termcolor" 123 | version = "1.4.0" 124 | source = "registry+https://github.com/rust-lang/crates.io-index" 125 | checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449" 126 | dependencies = [ 127 | "winapi-util", 128 | ] 129 | 130 | [[package]] 131 | name = "trybuild" 132 | version = "1.0.85" 133 | source = "registry+https://github.com/rust-lang/crates.io-index" 134 | checksum = "196a58260a906cedb9bf6d8034b6379d0c11f552416960452f267402ceeddff1" 135 | dependencies = [ 136 | "basic-toml", 137 | "dissimilar", 138 | "glob", 139 | "once_cell", 140 | "serde", 141 | "serde_derive", 142 | "serde_json", 143 | "termcolor", 144 | ] 145 | 146 | [[package]] 147 | name = "unicode-ident" 148 | version = "1.0.12" 149 | source = "registry+https://github.com/rust-lang/crates.io-index" 150 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 151 | 152 | [[package]] 153 | name = "winapi" 154 | version = "0.3.9" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 157 | dependencies = [ 158 | "winapi-i686-pc-windows-gnu", 159 | "winapi-x86_64-pc-windows-gnu", 160 | ] 161 | 162 | [[package]] 163 | name = "winapi-i686-pc-windows-gnu" 164 | version = "0.4.0" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 167 | 168 | [[package]] 169 | name = "winapi-util" 170 | version = "0.1.6" 171 | source = "registry+https://github.com/rust-lang/crates.io-index" 172 | checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" 173 | dependencies = [ 174 | "winapi", 175 | ] 176 | 177 | [[package]] 178 | name = "winapi-x86_64-pc-windows-gnu" 179 | version = "0.4.0" 180 | source = "registry+https://github.com/rust-lang/crates.io-index" 181 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 182 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sealed" 3 | version = "0.6.0" 4 | authors = ["José Duarte "] 5 | license = "MIT OR Apache-2.0" 6 | description = "Macro for sealing traits and structures" 7 | repository = "https://github.com/jmg-duarte/sealed-rs" 8 | documentation = "https://docs.rs/sealed" 9 | categories = ["development-tools", "rust-patterns"] 10 | keywords = ["proc_macro", "sealed", "future-proofing"] 11 | readme = "README.md" 12 | edition = "2021" 13 | exclude = ["images/*"] 14 | rust-version = "1.61.0" 15 | 16 | [workspace] 17 | members = ["demo"] 18 | 19 | [lib] 20 | proc-macro = true 21 | 22 | [dev-dependencies] 23 | trybuild = { version = "1.0", features = ["diff"] } 24 | syn = { version = "2.0", features = ["extra-traits"] } 25 | 26 | [dependencies] 27 | syn = { version = "2.0", features = ["full"] } 28 | quote = "1.0" 29 | proc-macro2 = "1.0" 30 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 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 [yyyy] [name of copyright owner] 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. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # `#[sealed]` 4 | 5 | [](https://docs.rs/sealed) 6 | [](https://crates.io/crates/sealed) 7 | MSRV 1.61.0 8 | 9 | This crate provides a convenient and simple way to implement the sealed trait pattern, 10 | as described in the Rust API Guidelines [[1](https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed)]. 11 | 12 | ```toml 13 | [dependencies] 14 | sealed = "0.6" 15 | ``` 16 | 17 | ## Example 18 | 19 | In the following code structs `A` and `B` implement the sealed trait `T`, 20 | the `C` struct, which is not sealed, will error during compilation. 21 | 22 | Examples are available in [`examples/`](examples/), you can also see a demo in [`demo/`](demo/). 23 | 24 | ```rust 25 | use sealed::sealed; 26 | 27 | #[sealed] 28 | trait T {} 29 | 30 | pub struct A; 31 | 32 | #[sealed] 33 | impl T for A {} 34 | 35 | pub struct B; 36 | 37 | #[sealed] 38 | impl T for B {} 39 | 40 | pub struct C; 41 | 42 | impl T for C {} // compile error 43 | ``` 44 | 45 | ## Arguments 46 | 47 | This is the list of arguments that can be used in a `#[sealed]` attribute: 48 | 49 | - `#[sealed(erase)]`: turns on trait bounds erasure. This is useful when using the `#[sealed]` macro inside a function. For an example, see [`bound-erasure-fn`](examples/bound-erasure-fn.rs) example. 50 | 51 | - `#[sealed(pub(crate))]` or `#[sealed(pub(in some::path))]`: allows to tune visibility of the generated sealing module (the default one is private). This useful when the trait and its impls are defined in different modules. For an example, see [`nesting`](examples/nesting.rs) example. **Notice**, that just `pub` is disallowed as breaks the whole idea of sealing. 52 | 53 | ### Contributing 54 | 55 | See [CONTRIBUTING.md](CONTRIBUTING.md). 56 | 57 | #### License 58 | 59 | 60 | Licensed under either of Apache License, Version 61 | 2.0 or MIT license at your option. 62 | 63 | 64 |
65 | 66 | 67 | Unless you explicitly state otherwise, any contribution intentionally submitted 68 | for inclusion in this project by you, as defined in the Apache-2.0 license, 69 | shall be dual licensed as above, without any additional terms or conditions. 70 | 71 | -------------------------------------------------------------------------------- /demo/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "demo" 5 | version = "0.1.0" 6 | dependencies = [ 7 | "sealed", 8 | ] 9 | 10 | [[package]] 11 | name = "proc-macro2" 12 | version = "1.0.24" 13 | source = "registry+https://github.com/rust-lang/crates.io-index" 14 | checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" 15 | dependencies = [ 16 | "unicode-xid", 17 | ] 18 | 19 | [[package]] 20 | name = "quote" 21 | version = "1.0.7" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37" 24 | dependencies = [ 25 | "proc-macro2", 26 | ] 27 | 28 | [[package]] 29 | name = "sealed" 30 | version = "0.1.1" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "d86fbdbe4c4c9b133f3833cef5fd0e7b47af185f4168d08fc93c835dd9e73ce9" 33 | dependencies = [ 34 | "proc-macro2", 35 | "quote", 36 | "syn", 37 | ] 38 | 39 | [[package]] 40 | name = "syn" 41 | version = "1.0.54" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | checksum = "9a2af957a63d6bd42255c359c93d9bfdb97076bd3b820897ce55ffbfbf107f44" 44 | dependencies = [ 45 | "proc-macro2", 46 | "quote", 47 | "unicode-xid", 48 | ] 49 | 50 | [[package]] 51 | name = "unicode-xid" 52 | version = "0.2.1" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 55 | -------------------------------------------------------------------------------- /demo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "demo" 3 | version = "0.1.0" 4 | authors = ["José Duarte "] 5 | edition = "2021" 6 | publish = false 7 | 8 | [dependencies] 9 | sealed = { path = ".." } 10 | -------------------------------------------------------------------------------- /demo/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use sealed::sealed; 4 | 5 | #[sealed] 6 | pub trait DroneState {} 7 | 8 | pub struct Drone 9 | where 10 | State: DroneState, 11 | { 12 | x: f32, 13 | y: f32, 14 | state: PhantomData, 15 | } 16 | 17 | pub struct Idle; 18 | #[sealed] 19 | impl DroneState for Idle {} 20 | 21 | pub struct Hovering; 22 | #[sealed] 23 | impl DroneState for Hovering {} 24 | 25 | pub struct Flying; 26 | #[sealed] 27 | impl DroneState for Flying {} 28 | 29 | impl Drone { 30 | #[must_use] 31 | pub fn new() -> Self { 32 | Self { 33 | state: PhantomData, 34 | x: 0.0, 35 | y: 0.0, 36 | } 37 | } 38 | 39 | #[must_use] 40 | pub fn take_off(self) -> Drone { 41 | Drone::::from(self) 42 | } 43 | } 44 | 45 | impl Default for Drone { 46 | fn default() -> Self { 47 | Self::new() 48 | } 49 | } 50 | 51 | impl Drone { 52 | #[must_use] 53 | fn land(self) -> Drone { 54 | Drone::::from(self) 55 | } 56 | 57 | #[must_use] 58 | fn move_to(self, x: f32, y: f32) -> Drone { 59 | let drone = Drone::::from(self); 60 | drone.fly(x, y) 61 | } 62 | } 63 | 64 | impl Drone { 65 | fn has_arrived(&self, x: f32, y: f32) -> bool { 66 | (self.x - x).abs() < f32::EPSILON && (self.y - y).abs() < f32::EPSILON 67 | } 68 | 69 | #[must_use] 70 | fn fly(mut self, x: f32, y: f32) -> Drone { 71 | while !self.has_arrived(x, y) { 72 | self.x = x; 73 | self.y = y; 74 | std::thread::sleep(std::time::Duration::from_millis(10)); 75 | } 76 | Drone::::from(self) 77 | } 78 | } 79 | 80 | impl From> for Drone { 81 | fn from(drone: Drone) -> Self { 82 | Self { 83 | x: drone.x, 84 | y: drone.y, 85 | state: PhantomData, 86 | } 87 | } 88 | } 89 | 90 | impl From> for Drone { 91 | fn from(drone: Drone) -> Self { 92 | Self { 93 | x: drone.x, 94 | y: drone.y, 95 | state: PhantomData, 96 | } 97 | } 98 | } 99 | 100 | impl From> for Drone { 101 | fn from(drone: Drone) -> Self { 102 | Self { 103 | x: drone.x, 104 | y: drone.y, 105 | state: PhantomData, 106 | } 107 | } 108 | } 109 | 110 | impl From> for Drone { 111 | fn from(drone: Drone) -> Self { 112 | Self { 113 | x: drone.x, 114 | y: drone.y, 115 | state: PhantomData, 116 | } 117 | } 118 | } 119 | 120 | #[cfg(test)] 121 | mod drone_test { 122 | use super::*; 123 | #[test] 124 | fn drone_spawns_idle() { 125 | let drone = Drone::::new(); 126 | assert!(drone.x.abs() < f32::EPSILON); 127 | assert!(drone.y.abs() < f32::EPSILON); 128 | } 129 | 130 | #[test] 131 | fn drone_takes_off_n_lands() { 132 | let drone = Drone::::new(); 133 | let drone = drone.take_off(); 134 | assert!(drone.x.abs() < f32::EPSILON); 135 | assert!(drone.y.abs() < f32::EPSILON); 136 | let _ = drone.land(); 137 | } 138 | 139 | #[test] 140 | fn drone_flies() { 141 | let drone = Drone::::new().take_off().move_to(-5.0, -5.0).land(); 142 | assert!((drone.x - -5.0).abs() < f32::EPSILON); 143 | assert!((drone.y - -5.0).abs() < f32::EPSILON); 144 | } 145 | 146 | #[test] 147 | fn drone_does_not_fly_idle() { 148 | let drone = Drone::::new(); 149 | // drone.move_to(10.0, 10.0); // comptime error: "move_to" is not a member of type Idle 150 | assert!(drone.x.abs() < f32::EPSILON); 151 | assert!(drone.y.abs() < f32::EPSILON); 152 | } 153 | } 154 | 155 | fn main() { 156 | let _drone = Drone::::new().take_off().move_to(-5.0, -5.0).land(); 157 | } 158 | -------------------------------------------------------------------------------- /examples/bound-erasure-fn.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | fn main() { 4 | trait Foo {} 5 | trait Bar {} 6 | 7 | #[sealed(erase)] 8 | trait Trait {} 9 | 10 | struct Implementor {} 11 | 12 | #[sealed(erase)] 13 | impl Trait for Implementor where T: Foo + Bar {} 14 | } 15 | -------------------------------------------------------------------------------- /examples/bound-erasure.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | trait Foo {} 4 | 5 | #[sealed(erase)] 6 | trait Trait {} 7 | 8 | fn main() {} 9 | -------------------------------------------------------------------------------- /examples/generics.rs: -------------------------------------------------------------------------------- 1 | // Test provided in #4 2 | // https://github.com/jmg-duarte/sealed-rs/issues/4 3 | 4 | use sealed::sealed; 5 | 6 | #[sealed] 7 | pub trait Set {} 8 | 9 | #[sealed] 10 | impl Set> for T {} 11 | 12 | #[sealed] 13 | impl Set> for Option {} 14 | 15 | fn main() {} 16 | -------------------------------------------------------------------------------- /examples/nesting.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(pub(crate))] 9 | pub trait LongerSnakeCaseType {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | pub struct B(i32); 18 | 19 | #[sealed] 20 | impl lets::attempt::some::nesting::LongerSnakeCaseType for A {} 21 | 22 | #[sealed] 23 | impl lets::attempt::some::nesting::LongerSnakeCaseType for B {} 24 | 25 | fn main() {} 26 | -------------------------------------------------------------------------------- /examples/raw-ident.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait r#Pub {} 5 | 6 | #[sealed] 7 | impl r#Pub> for T {} 8 | 9 | #[sealed] 10 | impl r#Pub> for Option {} 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait T {} 5 | 6 | pub struct A; 7 | pub struct B(i32); 8 | 9 | #[sealed] 10 | impl T for A {} 11 | #[sealed] 12 | impl T for B {} 13 | 14 | fn main() {} 15 | -------------------------------------------------------------------------------- /examples/syn.rs: -------------------------------------------------------------------------------- 1 | // Example provided in #4 2 | // https://github.com/jmg-duarte/sealed-rs/issues/4 3 | 4 | use proc_macro2::*; 5 | use sealed::sealed; 6 | use syn::spanned::Spanned; 7 | 8 | #[sealed] 9 | pub trait AsSpan { 10 | fn as_span(&self) -> Span; 11 | } 12 | // expands to: 13 | // pub trait AsSpan: __seal_as_span::Sealed { 14 | // fn as_span(&self) -> Span; 15 | // } 16 | // mod __seal_as_span { 17 | // pub trait Sealed {} 18 | // } 19 | 20 | #[sealed] 21 | impl AsSpan for Span { 22 | fn as_span(&self) -> Self { 23 | *self 24 | } 25 | } 26 | // expands to: 27 | // impl AsSpan for Span { // foreign type, cannot place #[sealed] 28 | // fn as_span(&self) -> Self { *self } 29 | // } 30 | // impl __seal_as_span::Sealed for Span {} 31 | 32 | #[sealed] 33 | impl AsSpan for &T { 34 | fn as_span(&self) -> Span { 35 | self.span() 36 | } 37 | } 38 | // expands to: 39 | // impl AsSpan for &T { 40 | // fn as_span(&self) -> Span { self.span() } 41 | // } 42 | // impl __seal_as_span::Sealed for &T {} 43 | 44 | fn main() {} 45 | -------------------------------------------------------------------------------- /images/sealed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmg-duarte/sealed-rs/8bd11ea70ea2610a6c3ae786d70367d950930a4c/images/sealed.png -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | 1.61.0 2 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # `#[sealed]` 2 | //! 3 | //! [](https://docs.rs/sealed) 4 | //! [](https://crates.io/crates/sealed) 5 | //! MSRV 1.51.0 6 | //! 7 | //! This crate provides a convenient and simple way to implement the sealed trait pattern, 8 | //! as described in the Rust API Guidelines [[1](https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed)]. 9 | //! 10 | //! ```toml 11 | //! [dependencies] 12 | //! sealed = "0.6" 13 | //! ``` 14 | //! 15 | //! ## Example 16 | //! 17 | //! In the following code structs `A` and `B` implement the sealed trait `T`, 18 | //! the `C` struct, which is not sealed, will error during compilation. 19 | //! 20 | //! You can see a demo in [`demo/`](demo/). 21 | //! 22 | //! ```rust,compile_fail 23 | //! # use sealed::sealed; 24 | //! # 25 | //! #[sealed] 26 | //! trait T {} 27 | //! 28 | //! pub struct A; 29 | //! #[sealed] 30 | //! impl T for A {} 31 | //! 32 | //! pub struct B; 33 | //! #[sealed] 34 | //! impl T for B {} 35 | //! 36 | //! pub struct C; 37 | //! impl T for C {} // compile error 38 | //! ``` 39 | //! 40 | //! ## Details 41 | //! 42 | //! The attribute generates a private uniquely named module when attached to a 43 | //! trait definition, when attached to an `impl` block the generated code simply 44 | //! implements the sealed trait for the respective type. 45 | //! 46 | //! ```rust,ignore 47 | //! // #[sealed] 48 | //! // trait T {} 49 | //! trait T: __seal_t::Sealed {} 50 | //! mod __seal_t { 51 | //! pub trait Sealed {} 52 | //! } 53 | //! 54 | //! pub struct A; 55 | //! 56 | //! // #[sealed] 57 | //! // impl T for A {} 58 | //! impl T for A {} 59 | //! impl __seal_t::Sealed for A {} 60 | //! ``` 61 | //! 62 | //! ## Arguments 63 | //! 64 | //! The expanded code may be customized with the following attribute arguments. 65 | //! 66 | //! ### `erase` 67 | //! 68 | //! Turns on trait bounds erasure. This is useful when using the `#[sealed]` 69 | //! attribute inside a function. By default, all the bounds are propagated to 70 | //! the generated `Sealed` trait. 71 | //! 72 | //! ```rust,ignore 73 | //! // #[sealed(erase)] 74 | //! // trait Trait {} 75 | //! trait Trait: __seal_trait::Sealed {} 76 | //! mod __seal_trait { 77 | //! pub trait Sealed {} 78 | //! } 79 | //! ``` 80 | //! 81 | //! ### `pub(crate)` or `pub(in some::path)` 82 | //! 83 | //! Allows to tune visibility of the generated sealing module (the default one 84 | //! is private). This useful when the trait and its impls are defined in 85 | //! different modules. 86 | //! 87 | //! ```rust 88 | //! # use sealed::sealed; 89 | //! # 90 | //! mod lets { 91 | //! pub mod attempt { 92 | //! pub mod some { 93 | //! pub mod nesting { 94 | //! # use sealed::sealed; 95 | //! #[sealed(pub(in super::super::super::super))] 96 | //! pub trait T {} 97 | //! } 98 | //! } 99 | //! } 100 | //! } 101 | //! 102 | //! pub struct A; 103 | //! #[sealed] 104 | //! impl lets::attempt::some::nesting::T for A {} 105 | //! ``` 106 | //! 107 | //! Notice, that just `pub` is disallowed as breaks the whole idea of sealing. 108 | //! 109 | //! ```rust,compile_fail 110 | //! # use sealed::sealed; 111 | //! # 112 | //! #[sealed(pub)] // compile error 113 | //! trait T {} 114 | //! 115 | //! pub struct A; 116 | //! #[sealed] 117 | //! impl T for A {} 118 | //! ``` 119 | 120 | use std::fmt; 121 | 122 | use proc_macro::TokenStream; 123 | use proc_macro2::{Span, TokenStream as TokenStream2}; 124 | use quote::{format_ident, quote}; 125 | use syn::{ 126 | ext::IdentExt, 127 | parse::{Parse, ParseStream}, 128 | parse_macro_input, parse_quote, 129 | spanned::Spanned, 130 | token, 131 | }; 132 | 133 | #[proc_macro_attribute] 134 | pub fn sealed(args: TokenStream, input: TokenStream) -> TokenStream { 135 | match parse_macro_input!(input) { 136 | syn::Item::Impl(item_impl) => parse_sealed_impl(&item_impl), 137 | syn::Item::Trait(item_trait) => { 138 | Ok(parse_sealed_trait(item_trait, parse_macro_input!(args))) 139 | } 140 | _ => Err(syn::Error::new(Span::call_site(), "expected impl or trait")), 141 | } 142 | .unwrap_or_else(|e| e.to_compile_error()) 143 | .into() 144 | } 145 | 146 | // Care for https://gist.github.com/Kestrer/8c05ebd4e0e9347eb05f265dfb7252e1#procedural-macros-support-renaming-the-crate 147 | fn parse_sealed_trait(mut item_trait: syn::ItemTrait, args: TraitArguments) -> TokenStream2 { 148 | let trait_ident = &item_trait.ident.unraw(); 149 | let trait_generics = &item_trait.generics; 150 | let trait_supertraits = &item_trait.supertraits; 151 | let seal = seal_name(trait_ident); 152 | let vis = &args.visibility; 153 | 154 | let (_, ty_generics, where_clause) = trait_generics.split_for_impl(); 155 | 156 | let mod_code = if args.erased { 157 | let lifetimes = trait_generics.lifetimes(); 158 | let const_params = trait_generics.const_params(); 159 | let type_params = 160 | trait_generics 161 | .type_params() 162 | .map(|syn::TypeParam { ident, .. }| -> syn::TypeParam { 163 | parse_quote!( #ident : ?Sized ) 164 | }); 165 | 166 | quote! { 167 | pub trait Sealed< #(#lifetimes ,)* #(#type_params ,)* #(#const_params ,)* > {} 168 | } 169 | } else { 170 | // `trait_generics` does not output its where clause when tokenized (due 171 | // to supertraits in the middle). So we output them separately. 172 | quote! { 173 | use super::*; 174 | pub trait Sealed #trait_generics : #trait_supertraits #where_clause {} 175 | } 176 | }; 177 | 178 | item_trait 179 | .supertraits 180 | .push(parse_quote!( #seal::Sealed #ty_generics )); 181 | quote! { 182 | #[automatically_derived] 183 | #vis mod #seal { 184 | #mod_code 185 | } 186 | #item_trait 187 | } 188 | } 189 | 190 | fn parse_sealed_impl(item_impl: &syn::ItemImpl) -> syn::Result { 191 | let impl_trait = item_impl 192 | .trait_ 193 | .as_ref() 194 | .ok_or_else(|| syn::Error::new_spanned(item_impl, "missing implementation trait"))?; 195 | 196 | let mut sealed_path = impl_trait.1.segments.clone(); 197 | 198 | // since `impl for ...` is not allowed, this path will *always* have at least length 1 199 | // thus both `first` and `last` are safe to unwrap 200 | let syn::PathSegment { ident, arguments } = sealed_path.pop().unwrap().into_value(); 201 | let seal = seal_name(ident.unraw()); 202 | sealed_path.push(parse_quote!( #seal )); 203 | sealed_path.push(parse_quote!(Sealed)); 204 | 205 | let self_type = &item_impl.self_ty; 206 | 207 | // Only keep the introduced params (no bounds), since 208 | // the bounds may break in the `#seal` submodule. 209 | let (trait_generics, _, where_clauses) = item_impl.generics.split_for_impl(); 210 | 211 | Ok(quote! { 212 | #[automatically_derived] 213 | impl #trait_generics #sealed_path #arguments for #self_type #where_clauses {} 214 | #item_impl 215 | }) 216 | } 217 | 218 | /// Convert a string into snake case. 219 | /// 220 | /// Stolen't from 221 | fn to_snake_case(s: &'_ str) -> String { 222 | let mut ret = String::with_capacity(s.len()); 223 | let mut first = true; 224 | s.bytes().for_each(|c| { 225 | if c.is_ascii_uppercase() { 226 | if !first { 227 | ret.push('_'); 228 | } 229 | ret.push(c.to_ascii_lowercase() as char); 230 | } else { 231 | ret.push(c as char); 232 | } 233 | first = false; 234 | }); 235 | ret 236 | } 237 | 238 | /// Constructs [`syn::Ident`] of a sealing module name. 239 | fn seal_name(seal: D) -> syn::Ident { 240 | format_ident!("__seal_{}", to_snake_case(&seal.to_string())) 241 | } 242 | 243 | /// Arguments accepted by `#[sealed]` attribute when placed on a trait 244 | /// definition. 245 | struct TraitArguments { 246 | /// `erase` argument indicating whether trait bounds erasure should be used. 247 | /// 248 | /// Default is `false`. 249 | erased: bool, 250 | 251 | /// `pub` argument defining visibility of the generated sealing module. 252 | /// 253 | /// Default is [`syn::Visibility::Inherited`]. 254 | visibility: syn::Visibility, 255 | } 256 | 257 | impl Default for TraitArguments { 258 | fn default() -> Self { 259 | Self { 260 | erased: false, 261 | visibility: syn::Visibility::Inherited, 262 | } 263 | } 264 | } 265 | 266 | impl Parse for TraitArguments { 267 | fn parse(input: ParseStream<'_>) -> syn::Result { 268 | let mut out = Self::default(); 269 | 270 | while !input.is_empty() { 271 | let ident = syn::Ident::parse_any(&input.fork())?; 272 | 273 | match ident.to_string().as_str() { 274 | "erase" => { 275 | syn::Ident::parse_any(input)?; 276 | out.erased = true; 277 | } 278 | 279 | "pub" => { 280 | out.visibility = input.parse()?; 281 | if matches!(out.visibility, syn::Visibility::Public(_)) { 282 | return Err(syn::Error::new( 283 | out.visibility.span(), 284 | "`pub` visibility breaks the seal as allows to use \ 285 | it outside its crate.\n\ 286 | Consider tightening the visibility (e.g. \ 287 | `pub(crate)`) if you actually need sealing.", 288 | )); 289 | } 290 | } 291 | 292 | unknown => { 293 | return Err(syn::Error::new( 294 | ident.span(), 295 | format!("unknown `{}` attribute argument", unknown), 296 | )) 297 | } 298 | } 299 | 300 | if input 301 | .lookahead1() 302 | .peek(token::Comma) 303 | .then(|| input.parse::()) 304 | .transpose()? 305 | .is_none() 306 | && !input.is_empty() 307 | { 308 | return Err(syn::Error::new(ident.span(), "expected followed by `,`")); 309 | } 310 | } 311 | 312 | Ok(out) 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /tests/fail/01-general.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | pub struct A; 4 | 5 | pub struct B { 6 | field_1: i32, 7 | } 8 | 9 | pub struct C; 10 | 11 | #[sealed] 12 | trait T {} 13 | 14 | #[sealed] 15 | impl T for A {} 16 | 17 | #[sealed] 18 | impl T for B {} 19 | 20 | impl T for C {} 21 | 22 | fn main() {} 23 | -------------------------------------------------------------------------------- /tests/fail/01-general.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `C: Sealed` is not satisfied 2 | --> tests/fail/01-general.rs:20:6 3 | | 4 | 20 | impl T for C {} 5 | | ^ the trait `Sealed` is not implemented for `C` 6 | | 7 | note: required by a bound in `T` 8 | --> tests/fail/01-general.rs:11:1 9 | | 10 | 11 | #[sealed] 11 | | ^^^^^^^^^ required by this bound in `T` 12 | 12 | trait T {} 13 | | - required by a bound in this 14 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 15 | -------------------------------------------------------------------------------- /tests/fail/02-nesting.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(pub(crate))] 9 | pub trait T {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | pub struct B { 17 | field_1: i32, 18 | } 19 | pub struct C; 20 | 21 | #[sealed] 22 | impl lets::attempt::some::nesting::T for A {} 23 | #[sealed] 24 | impl lets::attempt::some::nesting::T for B {} 25 | // fails to compile 26 | impl lets::attempt::some::nesting::T for C {} 27 | 28 | fn main() {} 29 | -------------------------------------------------------------------------------- /tests/fail/02-nesting.stderr: -------------------------------------------------------------------------------- 1 | error[E0277]: the trait bound `C: Sealed` is not satisfied 2 | --> tests/fail/02-nesting.rs:26:6 3 | | 4 | 26 | impl lets::attempt::some::nesting::T for C {} 5 | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Sealed` is not implemented for `C` 6 | | 7 | note: required by a bound in `T` 8 | --> tests/fail/02-nesting.rs:8:17 9 | | 10 | 8 | #[sealed(pub(crate))] 11 | | ^^^^^^^^^^^^^^^^^^^^^ required by this bound in `T` 12 | 9 | pub trait T {} 13 | | - required by a bound in this 14 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 15 | -------------------------------------------------------------------------------- /tests/fail/03-private-by-default.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed] 9 | pub trait T {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | #[sealed] 18 | impl lets::attempt::some::nesting::T for A {} 19 | 20 | fn main() {} 21 | -------------------------------------------------------------------------------- /tests/fail/03-private-by-default.stderr: -------------------------------------------------------------------------------- 1 | error[E0603]: module `__seal_t` is private 2 | --> tests/fail/03-private-by-default.rs:17:1 3 | | 4 | 17 | #[sealed] 5 | | ^^^^^^^^^ private module 6 | | 7 | note: the module `__seal_t` is defined here 8 | --> tests/fail/03-private-by-default.rs:8:17 9 | | 10 | 8 | #[sealed] 11 | | ^^^^^^^^^ 12 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 13 | -------------------------------------------------------------------------------- /tests/fail/04-no-full-pub.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(pub)] 9 | pub trait T {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | #[sealed] 18 | impl lets::attempt::some::nesting::T for A {} 19 | 20 | fn main() {} 21 | -------------------------------------------------------------------------------- /tests/fail/04-no-full-pub.stderr: -------------------------------------------------------------------------------- 1 | error: `pub` visibility breaks the seal as allows to use it outside its crate. 2 | Consider tightening the visibility (e.g. `pub(crate)`) if you actually need sealing. 3 | --> tests/fail/04-no-full-pub.rs:8:26 4 | | 5 | 8 | #[sealed(pub)] 6 | | ^^^ 7 | 8 | error[E0433]: failed to resolve: could not find `__seal_t` in `nesting` 9 | --> tests/fail/04-no-full-pub.rs:17:1 10 | | 11 | 17 | #[sealed] 12 | | ^^^^^^^^^ could not find `__seal_t` in `nesting` 13 | | 14 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 15 | 16 | error[E0405]: cannot find trait `T` in module `lets::attempt::some::nesting` 17 | --> tests/fail/04-no-full-pub.rs:18:36 18 | | 19 | 18 | impl lets::attempt::some::nesting::T for A {} 20 | | ^ not found in `lets::attempt::some::nesting` 21 | -------------------------------------------------------------------------------- /tests/fail/05-no-comma.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(erase pub(crate))] 9 | pub trait T {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | #[sealed] 18 | impl lets::attempt::some::nesting::T for A {} 19 | 20 | fn main() {} 21 | -------------------------------------------------------------------------------- /tests/fail/05-no-comma.stderr: -------------------------------------------------------------------------------- 1 | error: expected followed by `,` 2 | --> tests/fail/05-no-comma.rs:8:26 3 | | 4 | 8 | #[sealed(erase pub(crate))] 5 | | ^^^^^ 6 | 7 | error[E0433]: failed to resolve: could not find `__seal_t` in `nesting` 8 | --> tests/fail/05-no-comma.rs:17:1 9 | | 10 | 17 | #[sealed] 11 | | ^^^^^^^^^ could not find `__seal_t` in `nesting` 12 | | 13 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 14 | 15 | error[E0405]: cannot find trait `T` in module `lets::attempt::some::nesting` 16 | --> tests/fail/05-no-comma.rs:18:36 17 | | 18 | 18 | impl lets::attempt::some::nesting::T for A {} 19 | | ^ not found in `lets::attempt::some::nesting` 20 | -------------------------------------------------------------------------------- /tests/fail/06-wrong-argument.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed(erased)] 4 | pub trait T {} 5 | 6 | pub struct A; 7 | 8 | #[sealed] 9 | impl T for A {} 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /tests/fail/06-wrong-argument.stderr: -------------------------------------------------------------------------------- 1 | error: unknown `erased` attribute argument 2 | --> tests/fail/06-wrong-argument.rs:3:10 3 | | 4 | 3 | #[sealed(erased)] 5 | | ^^^^^^ 6 | 7 | error[E0433]: failed to resolve: use of undeclared crate or module `__seal_t` 8 | --> tests/fail/06-wrong-argument.rs:8:1 9 | | 10 | 8 | #[sealed] 11 | | ^^^^^^^^^ use of undeclared crate or module `__seal_t` 12 | | 13 | = note: this error originates in the attribute macro `sealed` (in Nightly builds, run with -Z macro-backtrace for more info) 14 | 15 | error[E0405]: cannot find trait `T` in this scope 16 | --> tests/fail/06-wrong-argument.rs:9:6 17 | | 18 | 9 | impl T for A {} 19 | | ^ not found in this scope 20 | -------------------------------------------------------------------------------- /tests/pass/01-long-name.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(pub(crate))] 9 | pub trait LongerSnakeCaseType {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | pub struct B { 18 | field_1: i32, 19 | } 20 | 21 | #[sealed] 22 | impl lets::attempt::some::nesting::LongerSnakeCaseType for A {} 23 | #[sealed] 24 | impl lets::attempt::some::nesting::LongerSnakeCaseType for B {} 25 | 26 | fn main() {} 27 | -------------------------------------------------------------------------------- /tests/pass/02-nesting.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | mod lets { 4 | pub mod attempt { 5 | pub mod some { 6 | pub mod nesting { 7 | use sealed::sealed; 8 | #[sealed(pub(in super::super::super::super))] 9 | pub trait T {} 10 | } 11 | } 12 | } 13 | } 14 | 15 | pub struct A; 16 | 17 | pub struct B { 18 | field_1: i32, 19 | } 20 | 21 | #[sealed] 22 | impl lets::attempt::some::nesting::T for A {} 23 | 24 | #[sealed] 25 | impl lets::attempt::some::nesting::T for B {} 26 | 27 | fn main() {} 28 | -------------------------------------------------------------------------------- /tests/pass/03-generics.rs: -------------------------------------------------------------------------------- 1 | // Test provided in #4 2 | // https://github.com/jmg-duarte/sealed-rs/issues/4 3 | 4 | use sealed::sealed; 5 | 6 | #[sealed] 7 | pub trait Set {} 8 | // pub trait Set: __seal_for_set::Sealed {} 9 | // mod __seal_for_set { 10 | // pub trait Sealed {} 11 | // } 12 | 13 | #[sealed] 14 | impl Set> for T {} 15 | // impl __seal_for_set::Sealed> for T {} 16 | 17 | #[sealed] 18 | impl Set> for Option {} 19 | // impl __seal_for_set::Sealed> for Option {} 20 | 21 | fn main() {} 22 | -------------------------------------------------------------------------------- /tests/pass/04-multiple-traits.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait T {} 5 | 6 | #[sealed] 7 | pub trait T1 {} 8 | 9 | pub struct A; 10 | pub struct B(i32); 11 | 12 | #[sealed] 13 | impl T for A {} 14 | #[sealed] 15 | impl T for B {} 16 | 17 | #[sealed] 18 | impl T1 for A {} 19 | #[sealed] 20 | impl T1 for B {} 21 | 22 | fn main() {} 23 | -------------------------------------------------------------------------------- /tests/pass/05-raw-ident.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait r#Pub {} 5 | 6 | #[sealed] 7 | impl r#Pub> for T {} 8 | 9 | #[sealed] 10 | impl r#Pub> for Option {} 11 | 12 | fn main() {} 13 | -------------------------------------------------------------------------------- /tests/pass/06-bounds.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | trait Foo {} 4 | 5 | #[sealed(erase)] 6 | trait Trait {} 7 | 8 | fn main() {} 9 | -------------------------------------------------------------------------------- /tests/pass/07-bound-erasure.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | trait Foo {} 4 | trait Bar {} 5 | 6 | #[sealed(erase)] 7 | trait Trait 8 | where 9 | T: ?Sized + Foo, 10 | { 11 | } 12 | 13 | struct Implementor {} 14 | 15 | #[sealed(erase)] 16 | impl Trait for Implementor where T: Foo + Bar {} 17 | 18 | fn main() {} 19 | -------------------------------------------------------------------------------- /tests/pass/08-bound-erasure-fn.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | fn main() { 4 | trait Foo {} 5 | trait Bar {} 6 | 7 | #[sealed(erase)] 8 | trait Trait 9 | where 10 | T: ?Sized + Foo, 11 | { 12 | } 13 | 14 | struct Implementor {} 15 | 16 | #[sealed(erase)] 17 | impl Trait for Implementor where T: Foo + Bar {} 18 | } 19 | -------------------------------------------------------------------------------- /tests/pass/09-enum.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | pub enum Enum {} 4 | 5 | #[sealed] 6 | pub trait Sealer {} 7 | 8 | #[sealed] 9 | impl Sealer for Enum {} 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /tests/pass/10-all-arguments.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | pub enum Enum {} 4 | 5 | #[sealed(erase, pub(crate))] 6 | pub trait Sealer {} 7 | 8 | #[sealed] 9 | impl Sealer for Enum {} 10 | 11 | fn main() {} 12 | -------------------------------------------------------------------------------- /tests/pass/11-where.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait AsRef 5 | where 6 | T: ?Sized, 7 | { 8 | fn as_ref(&self) -> &T; 9 | } 10 | 11 | #[sealed] 12 | impl AsRef for String { 13 | fn as_ref(&self) -> &str { 14 | &*self 15 | } 16 | } 17 | 18 | fn main() {} 19 | -------------------------------------------------------------------------------- /tests/pass/12-lifetime.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait Deserialize<'de>: Sized { 5 | fn deserialize(deserializer: D) -> Option; 6 | } 7 | 8 | #[sealed] 9 | impl<'de> Deserialize<'de> for () { 10 | fn deserialize(_deserializer: D) -> Option { 11 | Some(()) 12 | } 13 | } 14 | 15 | fn main() {} 16 | -------------------------------------------------------------------------------- /tests/pass/13-const-generics.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait FromArray { 5 | fn from(arr: [T; N]) -> Self; 6 | } 7 | 8 | #[sealed] 9 | impl FromArray for Vec { 10 | fn from(arr: [T; N]) -> Self { 11 | let mut v = Vec::with_capacity(N); 12 | for i in 0..N { 13 | v[i] = arr[i]; 14 | } 15 | v 16 | } 17 | } 18 | 19 | fn main() {} 20 | -------------------------------------------------------------------------------- /tests/pass/14-supertrait.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | #[sealed] 4 | pub trait CopyIterator: Iterator 5 | where 6 | Self::Item: Copy, 7 | { 8 | } 9 | 10 | fn main() {} 11 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn compile_test() { 3 | let t = trybuild::TestCases::new(); 4 | t.pass("tests/pass/*.rs"); 5 | t.compile_fail("tests/fail/*.rs"); 6 | } 7 | --------------------------------------------------------------------------------