diff --git a/Cargo.toml b/Cargo.toml index 2c401b985..abc514455 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,8 +59,8 @@ futures = "0.3.30" futures-util = "0.3.30" go-defer = "0.1.0" russh = "0.52" -axum = "0.8.1" -axum-extra = "0.10.0" +axum = "0.8.4" +axum-extra = "0.10.1" tower-http = "0.6.1" tower = "0.5.2" hex = "0.4.3" diff --git a/libra/src/utils/client_storage.rs b/libra/src/utils/client_storage.rs index 7ecc699ee..a464aa62f 100644 --- a/libra/src/utils/client_storage.rs +++ b/libra/src/utils/client_storage.rs @@ -382,6 +382,7 @@ mod tests { use super::ClientStorage; #[test] + #[ignore] fn test_content_store() { let content = "Hello, world!"; let blob = Blob::from_content(content); diff --git a/third-party/BUCK b/third-party/BUCK index 5c836fa7f..3cc4a5c5d 100644 --- a/third-party/BUCK +++ b/third-party/BUCK @@ -10150,7 +10150,7 @@ cargo.rust_library( deps = [ ":displaydoc-0.2.5", ":yoke-0.7.4", - ":zerofrom-0.1.4", + "//third-party/rust/crates/zerofrom/0.1.4:zerofrom", ":zerovec-0.10.4", ], ) @@ -10513,11 +10513,11 @@ cargo.rust_library( ":displaydoc-0.2.5", ":icu_locid-1.5.0", ":icu_provider_macros-1.5.0", - ":stable_deref_trait-1.2.0", + "//third-party/rust/crates/stable_deref_trait/1.2.0:stable_deref_trait", ":tinystr-0.7.6", "//third-party/rust/crates/writeable/0.5.5:writeable", ":yoke-0.7.4", - ":zerofrom-0.1.4", + "//third-party/rust/crates/zerofrom/0.1.4:zerofrom", ":zerovec-0.10.4", ], ) @@ -21339,16 +21339,6 @@ cargo.rust_library( ], ) -cargo.rust_library( - name = "stable_deref_trait-1.2.0", - srcs = ["vendor/stable_deref_trait-1.2.0/src/lib.rs"], - crate = "stable_deref_trait", - crate_root = "vendor/stable_deref_trait-1.2.0/src/lib.rs", - edition = "2015", - features = ["alloc"], - visibility = [], -) - cargo.rust_library( name = "stacker-0.1.17", srcs = ["vendor/stacker-0.1.17/src/lib.rs"], @@ -21485,26 +21475,7 @@ cargo.rust_library( deps = [":futures-core-0.3.31"], ) -cargo.rust_library( - name = "synstructure-0.13.1", - srcs = [ - "vendor/synstructure-0.13.1/src/lib.rs", - "vendor/synstructure-0.13.1/src/macros.rs", - ], - crate = "synstructure", - crate_root = "vendor/synstructure-0.13.1/src/lib.rs", - edition = "2018", - features = [ - "default", - "proc-macro", - ], - visibility = [], - deps = [ - "//third-party/rust/crates/proc-macro2/1.0.94:proc-macro2", - "//third-party/rust/crates/quote/1.0.40:quote", - "//third-party/rust/crates/syn/2.0.100:syn", - ], -) + cargo.rust_library( name = "sysexits-0.7.14", @@ -24609,9 +24580,9 @@ cargo.rust_library( visibility = [], deps = [ "//third-party/rust/crates/serde/1.0.217:serde", - ":stable_deref_trait-1.2.0", + "//third-party/rust/crates/stable_deref_trait/1.2.0:stable_deref_trait", ":yoke-derive-0.7.4", - ":zerofrom-0.1.4", + "//third-party/rust/crates/zerofrom/0.1.4:zerofrom", ], ) @@ -24630,7 +24601,7 @@ cargo.rust_library( "//third-party/rust/crates/proc-macro2/1.0.94:proc-macro2", "//third-party/rust/crates/quote/1.0.40:quote", "//third-party/rust/crates/syn/2.0.100:syn", - ":synstructure-0.13.1", + "//third-party/rust/crates/synstructure/0.13.1:synstructure", ], ) @@ -24675,43 +24646,6 @@ cargo.rust_library( ], ) -cargo.rust_library( - name = "zerofrom-0.1.4", - srcs = [ - "vendor/zerofrom-0.1.4/src/lib.rs", - "vendor/zerofrom-0.1.4/src/macro_impls.rs", - "vendor/zerofrom-0.1.4/src/zero_from.rs", - ], - crate = "zerofrom", - crate_root = "vendor/zerofrom-0.1.4/src/lib.rs", - edition = "2021", - features = [ - "alloc", - "derive", - ], - visibility = [], - deps = [":zerofrom-derive-0.1.4"], -) - -cargo.rust_library( - name = "zerofrom-derive-0.1.4", - srcs = [ - "vendor/zerofrom-derive-0.1.4/src/lib.rs", - "vendor/zerofrom-derive-0.1.4/src/visitor.rs", - ], - crate = "zerofrom_derive", - crate_root = "vendor/zerofrom-derive-0.1.4/src/lib.rs", - edition = "2021", - proc_macro = True, - visibility = [], - deps = [ - "//third-party/rust/crates/proc-macro2/1.0.94:proc-macro2", - "//third-party/rust/crates/quote/1.0.40:quote", - "//third-party/rust/crates/syn/2.0.100:syn", - ":synstructure-0.13.1", - ], -) - cargo.rust_library( name = "zerovec-0.10.4", srcs = [ @@ -24777,7 +24711,7 @@ cargo.rust_library( visibility = [], deps = [ ":yoke-0.7.4", - ":zerofrom-0.1.4", + "//third-party/rust/crates/zerofrom/0.1.4:zerofrom", "//third-party/rust/crates/zerovec-derive/0.10.3:zerovec-derive", ], ) diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/.cargo_vcs_info.json b/third-party/rust/crates/stable_deref_trait/1.2.0/.cargo_vcs_info.json new file mode 100644 index 000000000..4cf101dd3 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/.cargo_vcs_info.json @@ -0,0 +1,5 @@ +{ + "git": { + "sha1": "66f9d8a15b7209c45f58edee6c1b6bb497b7bd31" + } +} diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/.gitignore b/third-party/rust/crates/stable_deref_trait/1.2.0/.gitignore new file mode 100644 index 000000000..a9d37c560 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/BUCK b/third-party/rust/crates/stable_deref_trait/1.2.0/BUCK new file mode 100644 index 000000000..5ad6fdcb4 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/BUCK @@ -0,0 +1,11 @@ +load("@prelude//rust:cargo_package.bzl", "cargo") + +cargo.rust_library( + name = "stable_deref_trait", + srcs = glob(["src/**/*.rs"]), + crate = "stable_deref_trait", + crate_root = "src/lib.rs", + edition = "2015", + features = ["alloc"], + visibility = ["PUBLIC"], +) \ No newline at end of file diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml b/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml new file mode 100644 index 000000000..6bc26c3d3 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml @@ -0,0 +1,27 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "stable_deref_trait" +version = "1.2.0" +authors = ["Robert Grosse "] +description = "An unsafe marker trait for types like Box and Rc that dereference to a stable address even when moved, and hence can be used with libraries such as owning_ref and rental.\n" +documentation = "https://docs.rs/stable_deref_trait/1.2.0/stable_deref_trait" +readme = "README.md" +categories = ["memory-management", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/storyyeller/stable_deref_trait" + +[features] +alloc = [] +default = ["std"] +std = ["alloc"] diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml.orig b/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml.orig new file mode 100644 index 000000000..04e30b482 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/Cargo.toml.orig @@ -0,0 +1,17 @@ +[package] +name = "stable_deref_trait" +version = "1.2.0" +authors = ["Robert Grosse "] +license = "MIT/Apache-2.0" +readme = "README.md" +repository = "https://github.com/storyyeller/stable_deref_trait" +documentation = "https://docs.rs/stable_deref_trait/1.2.0/stable_deref_trait" +categories = ["memory-management", "no-std"] +description = """ +An unsafe marker trait for types like Box and Rc that dereference to a stable address even when moved, and hence can be used with libraries such as owning_ref and rental. +""" + +[features] +default = ["std"] +std = ["alloc"] +alloc = [] diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-APACHE b/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-APACHE new file mode 100644 index 000000000..16fe87b06 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-MIT b/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-MIT new file mode 100644 index 000000000..3bf61a090 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2017 Robert Grosse + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/README.md b/third-party/rust/crates/stable_deref_trait/1.2.0/README.md new file mode 100644 index 000000000..24fd4b099 --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/README.md @@ -0,0 +1,23 @@ +This crate defines an unsafe marker trait, StableDeref, for container types which deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address. + +It is intended to be used by crates such as [owning_ref](https://crates.io/crates/owning_ref) and [rental](https://crates.io/crates/rental), as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom Vec type together with owning_ref and rental. + +no_std support can be enabled by disabling default features (specifically "std"). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types. + +Enable the "alloc" feature (with default-features disabled) to have this trait be implemented for the above types from the built-in `alloc` crate, specifically +* `alloc::boxed::Box` +* `alloc::vec::Vec` +* `alloc::rc::Rc` +* `alloc::arc::Arc` +* `alloc::string::String` + +For example, this crate can be built with alloc support via the following command: +`cargo build --no-default-features --features alloc` + +Or added as a `Cargo.toml` dependency as follows: +``` +[dependencies.stable_deref_trait] +version = "" +default-features = false +features = [ "alloc" ] +``` diff --git a/third-party/rust/crates/stable_deref_trait/1.2.0/src/lib.rs b/third-party/rust/crates/stable_deref_trait/1.2.0/src/lib.rs new file mode 100644 index 000000000..069f6cc2e --- /dev/null +++ b/third-party/rust/crates/stable_deref_trait/1.2.0/src/lib.rs @@ -0,0 +1,189 @@ +// Copyright 2017 Robert Grosse + +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This module defines an unsafe marker trait, StableDeref, for container types that deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address. + +It is intended to be used by crates such as [owning_ref](https://crates.io/crates/owning_ref) and [rental](https://crates.io/crates/rental), as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom type together with owning_ref and rental. + +no_std support can be enabled by disabling default features (specifically "std"). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types. +*/ + +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "std")] +extern crate core; + +#[cfg(feature = "alloc")] +extern crate alloc; + +use core::ops::Deref; + + +/** +An unsafe marker trait for types that deref to a stable address, even when moved. For example, this is implemented by Box, Vec, Rc, Arc and String, among others. Even when a Box is moved, the underlying storage remains at a fixed location. + +More specifically, implementors must ensure that the result of calling deref() is valid for the lifetime of the object, not just the lifetime of the borrow, and that the deref is valid even if the object is moved. Also, it must be valid even after invoking arbitrary &self methods or doing anything transitively accessible from &Self. If Self also implements DerefMut, the same restrictions apply to deref_mut() and it must remain valid if anything transitively accessible from the result of deref_mut() is mutated/called. Additionally, multiple calls to deref, (and deref_mut if implemented) must return the same address. No requirements are placed on &mut self methods other than deref_mut() and drop(), if applicable. + +Basically, it must be valid to convert the result of deref() to a pointer, and later dereference that pointer, as long as the original object is still live, even if it has been moved or &self methods have been called on it. If DerefMut is also implemented, it must be valid to get pointers from deref() and deref_mut() and dereference them while the object is live, as long as you don't simultaneously dereference both of them. + +Additionally, Deref and DerefMut implementations must not panic, but users of the trait are not allowed to rely on this fact (so that this restriction can be removed later without breaking backwards compatibility, should the need arise). + +Here are some examples to help illustrate the requirements for implementing this trait: + +``` +# use std::ops::Deref; +struct Foo(u8); +impl Deref for Foo { + type Target = u8; + fn deref(&self) -> &Self::Target { &self.0 } +} +``` + +Foo cannot implement StableDeref because the int will move when Foo is moved, invalidating the result of deref(). + +``` +# use std::ops::Deref; +struct Foo(Box); +impl Deref for Foo { + type Target = u8; + fn deref(&self) -> &Self::Target { &*self.0 } +} +``` + +Foo can safely implement StableDeref, due to the use of Box. + + +``` +# use std::ops::Deref; +# use std::ops::DerefMut; +# use std::rc::Rc; +#[derive(Clone)] +struct Foo(Rc); +impl Deref for Foo { + type Target = u8; + fn deref(&self) -> &Self::Target { &*self.0 } +} +impl DerefMut for Foo { + fn deref_mut(&mut self) -> &mut Self::Target { Rc::make_mut(&mut self.0) } +} +``` + +This is a simple implementation of copy-on-write: Foo's deref_mut will copy the underlying int if it is not uniquely owned, ensuring unique access at the point where deref_mut() returns. However, Foo cannot implement StableDeref because calling deref_mut(), followed by clone().deref() will result in mutable and immutable references to the same location. Note that if the DerefMut implementation were removed, Foo could safely implement StableDeref. Likewise, if the Clone implementation were removed, it would be safe to implement StableDeref, although Foo would not be very useful in that case, (without clones, the rc will always be uniquely owned). + + +``` +# use std::ops::Deref; +struct Foo; +impl Deref for Foo { + type Target = str; + fn deref(&self) -> &Self::Target { &"Hello" } +} +``` +Foo can safely implement StableDeref. It doesn't own the data being derefed, but the data is gaurenteed to live long enough, due to it being 'static. + +``` +# use std::ops::Deref; +# use std::cell::Cell; +struct Foo(Cell); +impl Deref for Foo { + type Target = str; + fn deref(&self) -> &Self::Target { + let b = self.0.get(); + self.0.set(!b); + if b { &"Hello" } else { &"World" } + } +} +``` +Foo cannot safely implement StableDeref, even though every possible result of deref lives long enough. In order to safely implement StableAddress, multiple calls to deref must return the same result. + +``` +# use std::ops::Deref; +# use std::ops::DerefMut; +struct Foo(Box<(u8, u8)>); +impl Deref for Foo { + type Target = u8; + fn deref(&self) -> &Self::Target { &self.0.deref().0 } +} +impl DerefMut for Foo { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0.deref_mut().1 } +} +``` + +Foo cannot implement StableDeref because deref and deref_mut return different addresses. + + +*/ +pub unsafe trait StableDeref: Deref {} + +/** +An unsafe marker trait for types where clones deref to the same address. This has all the requirements of StableDeref, and additionally requires that after calling clone(), both the old and new value deref to the same address. For example, Rc and Arc implement CloneStableDeref, but Box and Vec do not. + +Note that a single type should never implement both DerefMut and CloneStableDeref. If it did, this would let you get two mutable references to the same location, by cloning and then calling deref_mut() on both values. +*/ +pub unsafe trait CloneStableDeref: StableDeref + Clone {} + +///////////////////////////////////////////////////////////////////////////// +// std types integration +///////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "alloc")] +use alloc::boxed::Box; +#[cfg(feature = "alloc")] +use alloc::rc::Rc; +#[cfg(feature = "alloc")] +use alloc::sync::Arc; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; +#[cfg(feature = "alloc")] +use alloc::string::String; + +#[cfg(feature = "std")] +use std::ffi::{CString, OsString}; +#[cfg(feature = "std")] +use std::path::PathBuf; +#[cfg(feature = "std")] +use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; + +use core::cell::{Ref, RefMut}; + + +#[cfg(feature = "alloc")] +unsafe impl StableDeref for Box {} +#[cfg(feature = "alloc")] +unsafe impl StableDeref for Vec {} +#[cfg(feature = "alloc")] +unsafe impl StableDeref for String {} +#[cfg(feature = "std")] +unsafe impl StableDeref for CString {} +#[cfg(feature = "std")] +unsafe impl StableDeref for OsString {} +#[cfg(feature = "std")] +unsafe impl StableDeref for PathBuf {} + +#[cfg(feature = "alloc")] +unsafe impl StableDeref for Rc {} +#[cfg(feature = "alloc")] +unsafe impl CloneStableDeref for Rc {} +#[cfg(feature = "alloc")] +unsafe impl StableDeref for Arc {} +#[cfg(feature = "alloc")] +unsafe impl CloneStableDeref for Arc {} + +unsafe impl<'a, T: ?Sized> StableDeref for Ref<'a, T> {} +unsafe impl<'a, T: ?Sized> StableDeref for RefMut<'a, T> {} +#[cfg(feature = "std")] +unsafe impl<'a, T: ?Sized> StableDeref for MutexGuard<'a, T> {} +#[cfg(feature = "std")] +unsafe impl<'a, T: ?Sized> StableDeref for RwLockReadGuard<'a, T> {} +#[cfg(feature = "std")] +unsafe impl<'a, T: ?Sized> StableDeref for RwLockWriteGuard<'a, T> {} + +unsafe impl<'a, T: ?Sized> StableDeref for &'a T {} +unsafe impl<'a, T: ?Sized> CloneStableDeref for &'a T {} +unsafe impl<'a, T: ?Sized> StableDeref for &'a mut T {} diff --git a/third-party/rust/crates/synstructure/0.13.1/.cargo_vcs_info.json b/third-party/rust/crates/synstructure/0.13.1/.cargo_vcs_info.json new file mode 100644 index 000000000..d3b07db15 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "875d166da5858b86122961ce6360acc771572d21" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/third-party/rust/crates/synstructure/0.13.1/BUCK b/third-party/rust/crates/synstructure/0.13.1/BUCK new file mode 100644 index 000000000..f1b0ef694 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/BUCK @@ -0,0 +1,19 @@ +load("@prelude//rust:cargo_package.bzl", "cargo") + +cargo.rust_library( + name = "synstructure", + srcs = glob(["src/**/*.rs"]), + crate = "synstructure", + crate_root = "src/lib.rs", + edition = "2018", + features = [ + "default", + "proc-macro", + ], + visibility = ["PUBLIC"], + deps = [ + "//third-party/rust/crates/proc-macro2/1.0.94:proc-macro2", + "//third-party/rust/crates/quote/1.0.40:quote", + "//third-party/rust/crates/syn/2.0.100:syn", + ], +) \ No newline at end of file diff --git a/third-party/rust/crates/synstructure/0.13.1/Cargo.toml b/third-party/rust/crates/synstructure/0.13.1/Cargo.toml new file mode 100644 index 000000000..50ceb9192 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/Cargo.toml @@ -0,0 +1,65 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "synstructure" +version = "0.13.1" +authors = ["Nika Layzell "] +include = [ + "src/**/*", + "Cargo.toml", + "README.md", + "LICENSE", +] +description = "Helper methods and macros for custom derives" +documentation = "https://docs.rs/synstructure" +readme = "README.md" +keywords = [ + "syn", + "macros", + "derive", + "expand_substructure", + "enum", +] +license = "MIT" +repository = "https://github.com/mystor/synstructure" + +[dependencies.proc-macro2] +version = "1.0.60" +default-features = false + +[dependencies.quote] +version = "1" +default-features = false + +[dependencies.syn] +version = "2" +features = [ + "derive", + "parsing", + "printing", + "clone-impls", + "visit", + "extra-traits", +] +default-features = false + +[dev-dependencies.synstructure_test_traits] +version = "0.1" + +[features] +default = ["proc-macro"] +proc-macro = [ + "proc-macro2/proc-macro", + "syn/proc-macro", + "quote/proc-macro", +] diff --git a/third-party/rust/crates/synstructure/0.13.1/Cargo.toml.orig b/third-party/rust/crates/synstructure/0.13.1/Cargo.toml.orig new file mode 100644 index 000000000..458b5cde7 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/Cargo.toml.orig @@ -0,0 +1,35 @@ +[package] +name = "synstructure" +version = "0.13.1" +authors = ["Nika Layzell "] +edition = "2018" + +description = "Helper methods and macros for custom derives" +documentation = "https://docs.rs/synstructure" +repository = "https://github.com/mystor/synstructure" +readme = "README.md" +license = "MIT" +keywords = ["syn", "macros", "derive", "expand_substructure", "enum"] + +include = ["src/**/*", "Cargo.toml", "README.md", "LICENSE"] + +[features] +default = ["proc-macro"] +proc-macro = ["proc-macro2/proc-macro", "syn/proc-macro", "quote/proc-macro"] + +[dependencies] +proc-macro2 = { version = "1.0.60", default-features = false } +quote = { version = "1", default-features = false } + +[dependencies.syn] +version = "2" +default-features = false +features = ["derive", "parsing", "printing", "clone-impls", "visit", "extra-traits"] + +[dev-dependencies] +# Used in the documentation as an example trait crate provider. Unfortunately, +# we need to publish this in order to be able to publish synstructure. +synstructure_test_traits = { version = "0.1", path = "test_traits" } + +[workspace] +members = ["test_traits", "test_suite", "test_suite/test_macros"] diff --git a/third-party/rust/crates/synstructure/0.13.1/LICENSE b/third-party/rust/crates/synstructure/0.13.1/LICENSE new file mode 100644 index 000000000..f78f1c15d --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/LICENSE @@ -0,0 +1,7 @@ +Copyright 2016 Nika Layzell + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third-party/rust/crates/synstructure/0.13.1/README.md b/third-party/rust/crates/synstructure/0.13.1/README.md new file mode 100644 index 000000000..1eefc1ed7 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/README.md @@ -0,0 +1,157 @@ +# synstructure + +[![Latest Version](https://img.shields.io/crates/v/synstructure.svg)](https://crates.io/crates/synstructure) +[![Documentation](https://docs.rs/synstructure/badge.svg)](https://docs.rs/synstructure) +[![Build Status](https://travis-ci.org/mystor/synstructure.svg?branch=master)](https://travis-ci.org/mystor/synstructure) +[![Rustc Version 1.31+](https://img.shields.io/badge/rustc-1.31+-lightgray.svg)](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html) + +> NOTE: What follows is an exerpt from the module level documentation. For full +> details read the docs on [docs.rs](https://docs.rs/synstructure/) + +This crate provides helper types for matching against enum variants, and +extracting bindings to each of the fields in the deriving Struct or Enum in +a generic way. + +If you are writing a `#[derive]` which needs to perform some operation on +every field, then you have come to the right place! + +# Example: `WalkFields` +### Trait Implementation +```rust +pub trait WalkFields: std::any::Any { + fn walk_fields(&self, walk: &mut FnMut(&WalkFields)); +} +impl WalkFields for i32 { + fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {} +} +``` + +### Custom Derive +```rust +#[macro_use] +extern crate synstructure; +#[macro_use] +extern crate quote; +extern crate proc_macro2; + +fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream { + let body = s.each(|bi| quote!{ + walk(#bi) + }); + + s.bound_impl(quote!(example_traits::WalkFields), quote!{ + fn walk_fields(&self, walk: &mut FnMut(&example_traits::WalkFields)) { + match *self { #body } + } + }) +} +decl_derive!([WalkFields] => walkfields_derive); + +/* + * Test Case + */ +fn main() { + test_derive! { + walkfields_derive { + enum A { + B(i32, T), + C(i32), + } + } + expands to { + const _: () = { + extern crate example_traits; + impl example_traits::WalkFields for A + where T: example_traits::WalkFields + { + fn walk_fields(&self, walk: &mut FnMut(&example_traits::WalkFields)) { + match *self { + A::B(ref __binding_0, ref __binding_1,) => { + { walk(__binding_0) } + { walk(__binding_1) } + } + A::C(ref __binding_0,) => { + { walk(__binding_0) } + } + } + } + } + }; + } + } +} +``` + +# Example: `Interest` +### Trait Implementation +```rust +pub trait Interest { + fn interesting(&self) -> bool; +} +impl Interest for i32 { + fn interesting(&self) -> bool { *self > 0 } +} +``` + +### Custom Derive +```rust +#[macro_use] +extern crate synstructure; +#[macro_use] +extern crate quote; +extern crate proc_macro2; + +fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream { + let body = s.fold(false, |acc, bi| quote!{ + #acc || example_traits::Interest::interesting(#bi) + }); + + s.bound_impl(quote!(example_traits::Interest), quote!{ + fn interesting(&self) -> bool { + match *self { + #body + } + } + }) +} +decl_derive!([Interest] => interest_derive); + +/* + * Test Case + */ +fn main() { + test_derive!{ + interest_derive { + enum A { + B(i32, T), + C(i32), + } + } + expands to { + const _: () = { + extern crate example_traits; + impl example_traits::Interest for A + where T: example_traits::Interest + { + fn interesting(&self) -> bool { + match *self { + A::B(ref __binding_0, ref __binding_1,) => { + false || + example_traits::Interest::interesting(__binding_0) || + example_traits::Interest::interesting(__binding_1) + } + A::C(ref __binding_0,) => { + false || + example_traits::Interest::interesting(__binding_0) + } + } + } + } + }; + } + } +} +``` + +For more example usage, consider investigating the `abomonation_derive` crate, +which makes use of this crate, and is fairly simple. diff --git a/third-party/rust/crates/synstructure/0.13.1/src/lib.rs b/third-party/rust/crates/synstructure/0.13.1/src/lib.rs new file mode 100644 index 000000000..0a63a39c2 --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/src/lib.rs @@ -0,0 +1,2556 @@ +//! This crate provides helper types for matching against enum variants, and +//! extracting bindings to each of the fields in the deriving Struct or Enum in +//! a generic way. +//! +//! If you are writing a `#[derive]` which needs to perform some operation on +//! every field, then you have come to the right place! +//! +//! # Example: `WalkFields` +//! ### Trait Implementation +//! ``` +//! pub trait WalkFields: std::any::Any { +//! fn walk_fields(&self, walk: &mut FnMut(&WalkFields)); +//! } +//! impl WalkFields for i32 { +//! fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {} +//! } +//! ``` +//! +//! ### Custom Derive +//! ``` +//! # use quote::quote; +//! fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream { +//! let body = s.each(|bi| quote!{ +//! walk(#bi) +//! }); +//! +//! s.gen_impl(quote! { +//! extern crate synstructure_test_traits; +//! +//! gen impl synstructure_test_traits::WalkFields for @Self { +//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) { +//! match *self { #body } +//! } +//! } +//! }) +//! } +//! # const _IGNORE: &'static str = stringify!( +//! synstructure::decl_derive!([WalkFields] => walkfields_derive); +//! # ); +//! +//! /* +//! * Test Case +//! */ +//! fn main() { +//! synstructure::test_derive! { +//! walkfields_derive { +//! enum A { +//! B(i32, T), +//! C(i32), +//! } +//! } +//! expands to { +//! const _: () = { +//! extern crate synstructure_test_traits; +//! impl synstructure_test_traits::WalkFields for A +//! where T: synstructure_test_traits::WalkFields +//! { +//! fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) { +//! match *self { +//! A::B(ref __binding_0, ref __binding_1,) => { +//! { walk(__binding_0) } +//! { walk(__binding_1) } +//! } +//! A::C(ref __binding_0,) => { +//! { walk(__binding_0) } +//! } +//! } +//! } +//! } +//! }; +//! } +//! } +//! } +//! ``` +//! +//! # Example: `Interest` +//! ### Trait Implementation +//! ``` +//! pub trait Interest { +//! fn interesting(&self) -> bool; +//! } +//! impl Interest for i32 { +//! fn interesting(&self) -> bool { *self > 0 } +//! } +//! ``` +//! +//! ### Custom Derive +//! ``` +//! # use quote::quote; +//! fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream { +//! let body = s.fold(false, |acc, bi| quote!{ +//! #acc || synstructure_test_traits::Interest::interesting(#bi) +//! }); +//! +//! s.gen_impl(quote! { +//! extern crate synstructure_test_traits; +//! gen impl synstructure_test_traits::Interest for @Self { +//! fn interesting(&self) -> bool { +//! match *self { +//! #body +//! } +//! } +//! } +//! }) +//! } +//! # const _IGNORE: &'static str = stringify!( +//! synstructure::decl_derive!([Interest] => interest_derive); +//! # ); +//! +//! /* +//! * Test Case +//! */ +//! fn main() { +//! synstructure::test_derive!{ +//! interest_derive { +//! enum A { +//! B(i32, T), +//! C(i32), +//! } +//! } +//! expands to { +//! const _: () = { +//! extern crate synstructure_test_traits; +//! impl synstructure_test_traits::Interest for A +//! where T: synstructure_test_traits::Interest +//! { +//! fn interesting(&self) -> bool { +//! match *self { +//! A::B(ref __binding_0, ref __binding_1,) => { +//! false || +//! synstructure_test_traits::Interest::interesting(__binding_0) || +//! synstructure_test_traits::Interest::interesting(__binding_1) +//! } +//! A::C(ref __binding_0,) => { +//! false || +//! synstructure_test_traits::Interest::interesting(__binding_0) +//! } +//! } +//! } +//! } +//! }; +//! } +//! } +//! } +//! ``` +//! +//! For more example usage, consider investigating the `abomonation_derive` crate, +//! which makes use of this crate, and is fairly simple. + +#![allow( + clippy::default_trait_access, + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::must_use_candidate, + clippy::needless_pass_by_value +)] + +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +extern crate proc_macro; + +use std::collections::HashSet; + +use syn::parse::{ParseStream, Parser}; +use syn::visit::{self, Visit}; +use syn::{ + braced, punctuated, token, Attribute, Data, DeriveInput, Error, Expr, Field, Fields, + FieldsNamed, FieldsUnnamed, GenericParam, Generics, Ident, PredicateType, Result, Token, + TraitBound, Type, TypeMacro, TypeParamBound, TypePath, WhereClause, WherePredicate, +}; + +use quote::{format_ident, quote_spanned, ToTokens}; +// re-export the quote! macro so we can depend on it being around in our macro's +// implementations. +#[doc(hidden)] +pub use quote::quote; + +use proc_macro2::{Span, TokenStream, TokenTree}; + +// NOTE: This module has documentation hidden, as it only exports macros (which +// always appear in the root of the crate) and helper methods / re-exports used +// in the implementation of those macros. +#[doc(hidden)] +pub mod macros; + +/// Changes how bounds are added +#[allow(clippy::manual_non_exhaustive)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum AddBounds { + /// Add for fields and generics + Both, + /// Fields only + Fields, + /// Generics only + Generics, + /// None + None, + #[doc(hidden)] + __Nonexhaustive, +} + +/// The type of binding to use when generating a pattern. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum BindStyle { + /// `x` + Move, + /// `mut x` + MoveMut, + /// `ref x` + Ref, + /// `ref mut x` + RefMut, +} + +impl ToTokens for BindStyle { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + BindStyle::Move => {} + BindStyle::MoveMut => quote_spanned!(Span::call_site() => mut).to_tokens(tokens), + BindStyle::Ref => quote_spanned!(Span::call_site() => ref).to_tokens(tokens), + BindStyle::RefMut => quote_spanned!(Span::call_site() => ref mut).to_tokens(tokens), + } + } +} + +// Internal method for merging seen_generics arrays together. +fn generics_fuse(res: &mut Vec, new: &[bool]) { + for (i, &flag) in new.iter().enumerate() { + if i == res.len() { + res.push(false); + } + if flag { + res[i] = true; + } + } +} + +// Internal method for extracting the set of generics which have been matched. +fn fetch_generics<'a>(set: &[bool], generics: &'a Generics) -> Vec<&'a Ident> { + let mut tys = vec![]; + for (&seen, param) in set.iter().zip(generics.params.iter()) { + if seen { + if let GenericParam::Type(tparam) = param { + tys.push(&tparam.ident); + } + } + } + tys +} + +// Internal method to merge two Generics objects together intelligently. +fn merge_generics(into: &mut Generics, from: &Generics) -> Result<()> { + // Try to add the param into `into`, and merge parmas with identical names. + for p in &from.params { + for op in &into.params { + match (op, p) { + (GenericParam::Type(otp), GenericParam::Type(tp)) => { + // NOTE: This is only OK because syn ignores the span for equality purposes. + if otp.ident == tp.ident { + return Err(Error::new_spanned( + p, + format!( + "Attempted to merge conflicting generic parameters: {} and {}", + quote!(#op), + quote!(#p) + ), + )); + } + } + (GenericParam::Lifetime(olp), GenericParam::Lifetime(lp)) => { + // NOTE: This is only OK because syn ignores the span for equality purposes. + if olp.lifetime == lp.lifetime { + return Err(Error::new_spanned( + p, + format!( + "Attempted to merge conflicting generic parameters: {} and {}", + quote!(#op), + quote!(#p) + ), + )); + } + } + // We don't support merging Const parameters, because that wouldn't make much sense. + _ => (), + } + } + into.params.push(p.clone()); + } + + // Add any where clauses from the input generics object. + if let Some(from_clause) = &from.where_clause { + into.make_where_clause() + .predicates + .extend(from_clause.predicates.iter().cloned()); + } + + Ok(()) +} + +/// Helper method which does the same thing as rustc 1.20's +/// `Option::get_or_insert_with`. This method is used to keep backwards +/// compatibility with rustc 1.15. +fn get_or_insert_with(opt: &mut Option, f: F) -> &mut T +where + F: FnOnce() -> T, +{ + if opt.is_none() { + *opt = Some(f()); + } + + match opt { + Some(v) => v, + None => unreachable!(), + } +} + +/// Information about a specific binding. This contains both an `Ident` +/// reference to the given field, and the syn `&'a Field` descriptor for that +/// field. +/// +/// This type supports `quote::ToTokens`, so can be directly used within the +/// `quote!` macro. It expands to a reference to the matched field. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct BindingInfo<'a> { + /// The name which this BindingInfo will bind to. + pub binding: Ident, + + /// The type of binding which this BindingInfo will create. + pub style: BindStyle, + + field: &'a Field, + + // These are used to determine which type parameters are avaliable. + generics: &'a Generics, + seen_generics: Vec, + // The original index of the binding + // this will not change when .filter() is called + index: usize, +} + +impl<'a> ToTokens for BindingInfo<'a> { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.binding.to_tokens(tokens); + } +} + +impl<'a> BindingInfo<'a> { + /// Returns a reference to the underlying `syn` AST node which this + /// `BindingInfo` references + pub fn ast(&self) -> &'a Field { + self.field + } + + /// Generates the pattern fragment for this field binding. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].bindings()[0].pat().to_string(), + /// quote! { + /// ref __binding_0 + /// }.to_string() + /// ); + /// ``` + pub fn pat(&self) -> TokenStream { + let BindingInfo { binding, style, .. } = self; + quote!(#style #binding) + } + + /// Returns a list of the type parameters which are referenced in this + /// field's type. + /// + /// # Caveat + /// + /// If the field contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// struct A { + /// a: Option, + /// b: U, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].bindings()[0].referenced_ty_params(), + /// &["e::format_ident!("T")] + /// ); + /// ``` + pub fn referenced_ty_params(&self) -> Vec<&'a Ident> { + fetch_generics(&self.seen_generics, self.generics) + } +} + +/// This type is similar to `syn`'s `Variant` type, however each of the fields +/// are references rather than owned. When this is used as the AST for a real +/// variant, this struct simply borrows the fields of the `syn::Variant`, +/// however this type may also be used as the sole variant for a struct. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct VariantAst<'a> { + pub attrs: &'a [Attribute], + pub ident: &'a Ident, + pub fields: &'a Fields, + pub discriminant: &'a Option<(token::Eq, Expr)>, +} + +/// A wrapper around a `syn::DeriveInput`'s variant which provides utilities +/// for destructuring `Variant`s with `match` expressions. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VariantInfo<'a> { + pub prefix: Option<&'a Ident>, + bindings: Vec>, + ast: VariantAst<'a>, + generics: &'a Generics, + // The original length of `bindings` before any `.filter()` calls + original_length: usize, +} + +/// Helper function used by the `VariantInfo` constructor. Walks all of the types +/// in `field` and returns a list of the type parameters from `ty_params` which +/// are referenced in the field. +fn get_ty_params(field: &Field, generics: &Generics) -> Vec { + // Helper type. Discovers all identifiers inside of the visited type, + // and calls a callback with them. + struct BoundTypeLocator<'a> { + result: Vec, + generics: &'a Generics, + } + + impl<'a> Visit<'a> for BoundTypeLocator<'a> { + // XXX: This also (intentionally) captures paths like T::SomeType. Is + // this desirable? + fn visit_ident(&mut self, id: &Ident) { + for (idx, i) in self.generics.params.iter().enumerate() { + if let GenericParam::Type(tparam) = i { + if tparam.ident == *id { + self.result[idx] = true; + } + } + } + } + + fn visit_type_macro(&mut self, x: &'a TypeMacro) { + // If we see a type_mac declaration, then we can't know what type parameters + // it might be binding, so we presume it binds all of them. + for r in &mut self.result { + *r = true; + } + visit::visit_type_macro(self, x); + } + } + + let mut btl = BoundTypeLocator { + result: vec![false; generics.params.len()], + generics, + }; + + btl.visit_type(&field.ty); + + btl.result +} + +impl<'a> VariantInfo<'a> { + fn new(ast: VariantAst<'a>, prefix: Option<&'a Ident>, generics: &'a Generics) -> Self { + let bindings = match ast.fields { + Fields::Unit => vec![], + Fields::Unnamed(FieldsUnnamed { + unnamed: fields, .. + }) + | Fields::Named(FieldsNamed { named: fields, .. }) => { + fields + .into_iter() + .enumerate() + .map(|(i, field)| { + BindingInfo { + // XXX: This has to be call_site to avoid privacy + // when deriving on private fields. + binding: format_ident!("__binding_{}", i), + style: BindStyle::Ref, + field, + generics, + seen_generics: get_ty_params(field, generics), + index: i, + } + }) + .collect::>() + } + }; + + let original_length = bindings.len(); + VariantInfo { + prefix, + bindings, + ast, + generics, + original_length, + } + } + + /// Returns a slice of the bindings in this Variant. + pub fn bindings(&self) -> &[BindingInfo<'a>] { + &self.bindings + } + + /// Returns a mut slice of the bindings in this Variant. + pub fn bindings_mut(&mut self) -> &mut [BindingInfo<'a>] { + &mut self.bindings + } + + /// Returns a `VariantAst` object which contains references to the + /// underlying `syn` AST node which this `Variant` was created from. + pub fn ast(&self) -> VariantAst<'a> { + self.ast + } + + /// True if any bindings were omitted due to a `filter` call. + pub fn omitted_bindings(&self) -> bool { + self.original_length != self.bindings.len() + } + + /// Generates the match-arm pattern which could be used to match against this Variant. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].pat().to_string(), + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) + /// }.to_string() + /// ); + /// ``` + pub fn pat(&self) -> TokenStream { + let mut t = TokenStream::new(); + if let Some(prefix) = self.prefix { + prefix.to_tokens(&mut t); + quote!(::).to_tokens(&mut t); + } + self.ast.ident.to_tokens(&mut t); + match self.ast.fields { + Fields::Unit => { + assert!(self.bindings.is_empty()); + } + Fields::Unnamed(..) => token::Paren(Span::call_site()).surround(&mut t, |t| { + let mut expected_index = 0; + for binding in &self.bindings { + while expected_index < binding.index { + quote!(_,).to_tokens(t); + expected_index += 1; + } + binding.pat().to_tokens(t); + quote!(,).to_tokens(t); + expected_index += 1; + } + if expected_index != self.original_length { + quote!(..).to_tokens(t); + } + }), + Fields::Named(..) => token::Brace(Span::call_site()).surround(&mut t, |t| { + for binding in &self.bindings { + binding.field.ident.to_tokens(t); + quote!(:).to_tokens(t); + binding.pat().to_tokens(t); + quote!(,).to_tokens(t); + } + if self.omitted_bindings() { + quote!(..).to_tokens(t); + } + }), + } + t + } + + /// Generates the token stream required to construct the current variant. + /// + /// The init array initializes each of the fields in the order they are + /// written in `variant.ast().fields`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(usize, usize), + /// C{ v: usize }, + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].construct(|_, i| quote!(#i)).to_string(), + /// + /// quote!{ + /// A::B(0usize, 1usize,) + /// }.to_string() + /// ); + /// + /// assert_eq!( + /// s.variants()[1].construct(|_, i| quote!(#i)).to_string(), + /// + /// quote!{ + /// A::C{ v: 0usize, } + /// }.to_string() + /// ); + /// ``` + pub fn construct(&self, mut func: F) -> TokenStream + where + F: FnMut(&Field, usize) -> T, + T: ToTokens, + { + let mut t = TokenStream::new(); + if let Some(prefix) = self.prefix { + quote!(#prefix ::).to_tokens(&mut t); + } + self.ast.ident.to_tokens(&mut t); + + match &self.ast.fields { + Fields::Unit => (), + Fields::Unnamed(FieldsUnnamed { unnamed, .. }) => { + token::Paren::default().surround(&mut t, |t| { + for (i, field) in unnamed.into_iter().enumerate() { + func(field, i).to_tokens(t); + quote!(,).to_tokens(t); + } + }); + } + Fields::Named(FieldsNamed { named, .. }) => { + token::Brace::default().surround(&mut t, |t| { + for (i, field) in named.into_iter().enumerate() { + field.ident.to_tokens(t); + quote!(:).to_tokens(t); + func(field, i).to_tokens(t); + quote!(,).to_tokens(t); + } + }); + } + } + t + } + + /// Runs the passed-in function once for each bound field, passing in a `BindingInfo`. + /// and generating a `match` arm which evaluates the returned tokens. + /// + /// This method will ignore fields which are ignored through the `filter` + /// method. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// { println!("{:?}", __binding_0) } + /// { println!("{:?}", __binding_1) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn each(&self, mut f: F) -> TokenStream + where + F: FnMut(&BindingInfo<'_>) -> R, + R: ToTokens, + { + let pat = self.pat(); + let mut body = TokenStream::new(); + for binding in &self.bindings { + token::Brace::default().surround(&mut body, |body| { + f(binding).to_tokens(body); + }); + } + quote!(#pat => { #body }) + } + + /// Runs the passed-in function once for each bound field, passing in the + /// result of the previous call, and a `BindingInfo`. generating a `match` + /// arm which evaluates to the resulting tokens. + /// + /// This method will ignore fields which are ignored through the `filter` + /// method. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// 0 + __binding_0 + __binding_1 + /// } + /// }.to_string() + /// ); + /// ``` + pub fn fold(&self, init: I, mut f: F) -> TokenStream + where + F: FnMut(TokenStream, &BindingInfo<'_>) -> R, + I: ToTokens, + R: ToTokens, + { + let pat = self.pat(); + let body = self.bindings.iter().fold(quote!(#init), |i, bi| { + let r = f(i, bi); + quote!(#r) + }); + quote!(#pat => { #body }) + } + + /// Filter the bindings created by this `Variant` object. This has 2 effects: + /// + /// * The bindings will no longer appear in match arms generated by methods + /// on this `Variant` or its subobjects. + /// + /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl` + /// method only consider type parameters referenced in the types of + /// non-filtered fields. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.variants_mut()[0].filter(|bi| { + /// bi.ast().ident == Some(quote::format_ident!("b")) + /// }); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ b: ref __binding_1, .. } => { + /// { println!("{:?}", __binding_1) } + /// } + /// A::C{ a: ref __binding_0, } => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn filter(&mut self, f: F) -> &mut Self + where + F: FnMut(&BindingInfo<'_>) -> bool, + { + self.bindings.retain(f); + self + } + + /// Iterates all the bindings of this `Variant` object and uses a closure to determine if a + /// binding should be removed. If the closure returns `true` the binding is removed from the + /// variant. If the closure returns `false`, the binding remains in the variant. + /// + /// All the removed bindings are moved to a new `Variant` object which is otherwise identical + /// to the current one. To understand the effects of removing a binding from a variant check + /// the [`VariantInfo::filter`] documentation. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// let mut with_b = &mut s.variants_mut()[0]; + /// + /// let with_a = with_b.drain_filter(|bi| { + /// bi.ast().ident == Some(quote::format_ident!("a")) + /// }); + /// + /// assert_eq!( + /// with_a.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ a: ref __binding_0, .. } => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// + /// assert_eq!( + /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ b: ref __binding_1, .. } => { + /// { println!("{:?}", __binding_1) } + /// } + /// }.to_string() + /// ); + /// ``` + #[allow(clippy::return_self_not_must_use)] + pub fn drain_filter(&mut self, mut f: F) -> Self + where + F: FnMut(&BindingInfo<'_>) -> bool, + { + let mut other = VariantInfo { + prefix: self.prefix, + bindings: vec![], + ast: self.ast, + generics: self.generics, + original_length: self.original_length, + }; + + let (other_bindings, self_bindings) = self.bindings.drain(..).partition(&mut f); + other.bindings = other_bindings; + self.bindings = self_bindings; + + other + } + + /// Remove the binding at the given index. + /// + /// # Panics + /// + /// Panics if the index is out of range. + pub fn remove_binding(&mut self, idx: usize) -> &mut Self { + self.bindings.remove(idx); + self + } + + /// Updates the `BindStyle` for each of the passed-in fields by calling the + /// passed-in function for each `BindingInfo`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.variants_mut()[0].bind_with(|bi| BindStyle::RefMut); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B(ref mut __binding_0, ref mut __binding_1,) => { + /// { println!("{:?}", __binding_0) } + /// { println!("{:?}", __binding_1) } + /// } + /// A::C(ref __binding_0,) => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn bind_with(&mut self, mut f: F) -> &mut Self + where + F: FnMut(&BindingInfo<'_>) -> BindStyle, + { + for binding in &mut self.bindings { + binding.style = f(binding); + } + self + } + + /// Updates the binding name for each fo the passed-in fields by calling the + /// passed-in function for each `BindingInfo`. + /// + /// The function will be called with the `BindingInfo` and its index in the + /// enclosing variant. + /// + /// The default name is `__binding_{}` where `{}` is replaced with an + /// increasing number. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.variants_mut()[0].binding_name(|bi, i| bi.ident.clone().unwrap()); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ a: ref a, b: ref b, } => { + /// { println!("{:?}", a) } + /// { println!("{:?}", b) } + /// } + /// A::C{ a: ref __binding_0, } => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn binding_name(&mut self, mut f: F) -> &mut Self + where + F: FnMut(&Field, usize) -> Ident, + { + for (it, binding) in self.bindings.iter_mut().enumerate() { + binding.binding = f(binding.field, it); + } + self + } + + /// Returns a list of the type parameters which are referenced in this + /// field's type. + /// + /// # Caveat + /// + /// If the field contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// struct A { + /// a: Option, + /// b: U, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// assert_eq!( + /// s.variants()[0].bindings()[0].referenced_ty_params(), + /// &["e::format_ident!("T")] + /// ); + /// ``` + pub fn referenced_ty_params(&self) -> Vec<&'a Ident> { + let mut flags = Vec::new(); + for binding in &self.bindings { + generics_fuse(&mut flags, &binding.seen_generics); + } + fetch_generics(&flags, self.generics) + } +} + +/// A wrapper around a `syn::DeriveInput` which provides utilities for creating +/// custom derive trait implementations. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Structure<'a> { + variants: Vec>, + omitted_variants: bool, + ast: &'a DeriveInput, + extra_impl: Vec, + extra_predicates: Vec, + add_bounds: AddBounds, +} + +impl<'a> Structure<'a> { + /// Create a new `Structure` with the variants and fields from the passed-in + /// `DeriveInput`. + /// + /// # Panics + /// + /// This method will panic if the provided AST node represents an untagged + /// union. + pub fn new(ast: &'a DeriveInput) -> Self { + Self::try_new(ast).expect("Unable to create synstructure::Structure") + } + + /// Create a new `Structure` with the variants and fields from the passed-in + /// `DeriveInput`. + /// + /// Unlike `Structure::new`, this method does not panic if the provided AST + /// node represents an untagged union. + pub fn try_new(ast: &'a DeriveInput) -> Result { + let variants = match &ast.data { + Data::Enum(data) => (&data.variants) + .into_iter() + .map(|v| { + VariantInfo::new( + VariantAst { + attrs: &v.attrs, + ident: &v.ident, + fields: &v.fields, + discriminant: &v.discriminant, + }, + Some(&ast.ident), + &ast.generics, + ) + }) + .collect::>(), + Data::Struct(data) => { + vec![VariantInfo::new( + VariantAst { + attrs: &ast.attrs, + ident: &ast.ident, + fields: &data.fields, + discriminant: &None, + }, + None, + &ast.generics, + )] + } + Data::Union(_) => { + return Err(Error::new_spanned( + ast, + "unexpected unsupported untagged union", + )); + } + }; + + Ok(Structure { + variants, + omitted_variants: false, + ast, + extra_impl: vec![], + extra_predicates: vec![], + add_bounds: AddBounds::Both, + }) + } + + /// Returns a slice of the variants in this Structure. + pub fn variants(&self) -> &[VariantInfo<'a>] { + &self.variants + } + + /// Returns a mut slice of the variants in this Structure. + pub fn variants_mut(&mut self) -> &mut [VariantInfo<'a>] { + &mut self.variants + } + + /// Returns a reference to the underlying `syn` AST node which this + /// `Structure` was created from. + pub fn ast(&self) -> &'a DeriveInput { + self.ast + } + + /// True if any variants were omitted due to a `filter_variants` call. + pub fn omitted_variants(&self) -> bool { + self.omitted_variants + } + + /// Runs the passed-in function once for each bound field, passing in a `BindingInfo`. + /// and generating `match` arms which evaluate the returned tokens. + /// + /// This method will ignore variants or fields which are ignored through the + /// `filter` and `filter_variant` methods. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// { println!("{:?}", __binding_0) } + /// { println!("{:?}", __binding_1) } + /// } + /// A::C(ref __binding_0,) => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn each(&self, mut f: F) -> TokenStream + where + F: FnMut(&BindingInfo<'_>) -> R, + R: ToTokens, + { + let mut t = TokenStream::new(); + for variant in &self.variants { + variant.each(&mut f).to_tokens(&mut t); + } + if self.omitted_variants { + quote!(_ => {}).to_tokens(&mut t); + } + t + } + + /// Runs the passed-in function once for each bound field, passing in the + /// result of the previous call, and a `BindingInfo`. generating `match` + /// arms which evaluate to the resulting tokens. + /// + /// This method will ignore variants or fields which are ignored through the + /// `filter` and `filter_variant` methods. + /// + /// If a variant has been ignored, it will return the `init` value. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// 0 + __binding_0 + __binding_1 + /// } + /// A::C(ref __binding_0,) => { + /// 0 + __binding_0 + /// } + /// }.to_string() + /// ); + /// ``` + pub fn fold(&self, init: I, mut f: F) -> TokenStream + where + F: FnMut(TokenStream, &BindingInfo<'_>) -> R, + I: ToTokens, + R: ToTokens, + { + let mut t = TokenStream::new(); + for variant in &self.variants { + variant.fold(&init, &mut f).to_tokens(&mut t); + } + if self.omitted_variants { + quote!(_ => { #init }).to_tokens(&mut t); + } + t + } + + /// Runs the passed-in function once for each variant, passing in a + /// `VariantInfo`. and generating `match` arms which evaluate the returned + /// tokens. + /// + /// This method will ignore variants and not bind fields which are ignored + /// through the `filter` and `filter_variant` methods. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let s = Structure::new(&di); + /// + /// assert_eq!( + /// s.each_variant(|v| { + /// let name = &v.ast().ident; + /// quote!(println!(stringify!(#name))) + /// }).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// println!(stringify!(B)) + /// } + /// A::C(ref __binding_0,) => { + /// println!(stringify!(C)) + /// } + /// }.to_string() + /// ); + /// ``` + pub fn each_variant(&self, mut f: F) -> TokenStream + where + F: FnMut(&VariantInfo<'_>) -> R, + R: ToTokens, + { + let mut t = TokenStream::new(); + for variant in &self.variants { + let pat = variant.pat(); + let body = f(variant); + quote!(#pat => { #body }).to_tokens(&mut t); + } + if self.omitted_variants { + quote!(_ => {}).to_tokens(&mut t); + } + t + } + + /// Filter the bindings created by this `Structure` object. This has 2 effects: + /// + /// * The bindings will no longer appear in match arms generated by methods + /// on this `Structure` or its subobjects. + /// + /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl` + /// method only consider type parameters referenced in the types of + /// non-filtered fields. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter(|bi| { + /// bi.ast().ident == Some(quote::format_ident!("a")) + /// }); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ a: ref __binding_0, .. } => { + /// { println!("{:?}", __binding_0) } + /// } + /// A::C{ a: ref __binding_0, } => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn filter(&mut self, mut f: F) -> &mut Self + where + F: FnMut(&BindingInfo<'_>) -> bool, + { + for variant in &mut self.variants { + variant.filter(&mut f); + } + self + } + + /// Iterates all the bindings of this `Structure` object and uses a closure to determine if a + /// binding should be removed. If the closure returns `true` the binding is removed from the + /// structure. If the closure returns `false`, the binding remains in the structure. + /// + /// All the removed bindings are moved to a new `Structure` object which is otherwise identical + /// to the current one. To understand the effects of removing a binding from a structure check + /// the [`Structure::filter`] documentation. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut with_b = Structure::new(&di); + /// + /// let with_a = with_b.drain_filter(|bi| { + /// bi.ast().ident == Some(quote::format_ident!("a")) + /// }); + /// + /// assert_eq!( + /// with_a.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ a: ref __binding_0, .. } => { + /// { println!("{:?}", __binding_0) } + /// } + /// A::C{ a: ref __binding_0, } => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// + /// assert_eq!( + /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ b: ref __binding_1, .. } => { + /// { println!("{:?}", __binding_1) } + /// } + /// A::C{ .. } => { + /// + /// } + /// }.to_string() + /// ); + /// ``` + #[allow(clippy::return_self_not_must_use)] + pub fn drain_filter(&mut self, mut f: F) -> Self + where + F: FnMut(&BindingInfo<'_>) -> bool, + { + Self { + variants: self + .variants + .iter_mut() + .map(|variant| variant.drain_filter(&mut f)) + .collect(), + omitted_variants: self.omitted_variants, + ast: self.ast, + extra_impl: self.extra_impl.clone(), + extra_predicates: self.extra_predicates.clone(), + add_bounds: self.add_bounds, + } + } + + /// Specify additional where predicate bounds which should be generated by + /// impl-generating functions such as `gen_impl`, `bound_impl`, and + /// `unsafe_bound_impl`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// // Add an additional where predicate. + /// s.add_where_predicate(syn::parse_quote!(T: std::fmt::Display)); + /// + /// assert_eq!( + /// s.bound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where T: std::fmt::Display, + /// T: krate::Trait, + /// Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn add_where_predicate(&mut self, pred: WherePredicate) -> &mut Self { + self.extra_predicates.push(pred); + self + } + + /// Specify which bounds should be generated by impl-generating functions + /// such as `gen_impl`, `bound_impl`, and `unsafe_bound_impl`. + /// + /// The default behaviour is to generate both field and generic bounds from + /// type parameters. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// // Limit bounds to only generics. + /// s.add_bounds(AddBounds::Generics); + /// + /// assert_eq!( + /// s.bound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where T: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn add_bounds(&mut self, mode: AddBounds) -> &mut Self { + self.add_bounds = mode; + self + } + + /// Filter the variants matched by this `Structure` object. This has 2 effects: + /// + /// * Match arms destructuring these variants will no longer be generated by + /// methods on this `Structure` + /// + /// * Impl blocks created with the `bound_impl` or `unsafe_bound_impl` + /// method only consider type parameters referenced in the types of + /// fields in non-fitered variants. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::C(ref __binding_0,) => { + /// { println!("{:?}", __binding_0) } + /// } + /// _ => {} + /// }.to_string() + /// ); + /// ``` + pub fn filter_variants(&mut self, f: F) -> &mut Self + where + F: FnMut(&VariantInfo<'_>) -> bool, + { + let before_len = self.variants.len(); + self.variants.retain(f); + if self.variants.len() != before_len { + self.omitted_variants = true; + } + self + } + /// Iterates all the variants of this `Structure` object and uses a closure to determine if a + /// variant should be removed. If the closure returns `true` the variant is removed from the + /// structure. If the closure returns `false`, the variant remains in the structure. + /// + /// All the removed variants are moved to a new `Structure` object which is otherwise identical + /// to the current one. To understand the effects of removing a variant from a structure check + /// the [`Structure::filter_variants`] documentation. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// + /// let mut with_c = Structure::new(&di); + /// + /// let with_b = with_c.drain_filter_variants(|v| v.ast().ident == "B"); + /// + /// assert_eq!( + /// with_c.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::C(ref __binding_0,) => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// + /// assert_eq!( + /// with_b.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B(ref __binding_0, ref __binding_1,) => { + /// { println!("{:?}", __binding_0) } + /// { println!("{:?}", __binding_1) } + /// } + /// }.to_string() + /// ); + #[allow(clippy::return_self_not_must_use)] + pub fn drain_filter_variants(&mut self, mut f: F) -> Self + where + F: FnMut(&VariantInfo<'_>) -> bool, + { + let mut other = Self { + variants: vec![], + omitted_variants: self.omitted_variants, + ast: self.ast, + extra_impl: self.extra_impl.clone(), + extra_predicates: self.extra_predicates.clone(), + add_bounds: self.add_bounds, + }; + + let (other_variants, self_variants) = self.variants.drain(..).partition(&mut f); + other.variants = other_variants; + self.variants = self_variants; + + other + } + + /// Remove the variant at the given index. + /// + /// # Panics + /// + /// Panics if the index is out of range. + pub fn remove_variant(&mut self, idx: usize) -> &mut Self { + self.variants.remove(idx); + self.omitted_variants = true; + self + } + + /// Updates the `BindStyle` for each of the passed-in fields by calling the + /// passed-in function for each `BindingInfo`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(i32, i32), + /// C(u32), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.bind_with(|bi| BindStyle::RefMut); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B(ref mut __binding_0, ref mut __binding_1,) => { + /// { println!("{:?}", __binding_0) } + /// { println!("{:?}", __binding_1) } + /// } + /// A::C(ref mut __binding_0,) => { + /// { println!("{:?}", __binding_0) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn bind_with(&mut self, mut f: F) -> &mut Self + where + F: FnMut(&BindingInfo<'_>) -> BindStyle, + { + for variant in &mut self.variants { + variant.bind_with(&mut f); + } + self + } + + /// Updates the binding name for each fo the passed-in fields by calling the + /// passed-in function for each `BindingInfo`. + /// + /// The function will be called with the `BindingInfo` and its index in the + /// enclosing variant. + /// + /// The default name is `__binding_{}` where `{}` is replaced with an + /// increasing number. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B{ a: i32, b: i32 }, + /// C{ a: u32 }, + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.binding_name(|bi, i| bi.ident.clone().unwrap()); + /// + /// assert_eq!( + /// s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), + /// + /// quote!{ + /// A::B{ a: ref a, b: ref b, } => { + /// { println!("{:?}", a) } + /// { println!("{:?}", b) } + /// } + /// A::C{ a: ref a, } => { + /// { println!("{:?}", a) } + /// } + /// }.to_string() + /// ); + /// ``` + pub fn binding_name(&mut self, mut f: F) -> &mut Self + where + F: FnMut(&Field, usize) -> Ident, + { + for variant in &mut self.variants { + variant.binding_name(&mut f); + } + self + } + + /// Returns a list of the type parameters which are refrenced in the types + /// of non-filtered fields / variants. + /// + /// # Caveat + /// + /// If the struct contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T, i32), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "C"); + /// + /// assert_eq!( + /// s.referenced_ty_params(), + /// &["e::format_ident!("T")] + /// ); + /// ``` + pub fn referenced_ty_params(&self) -> Vec<&'a Ident> { + let mut flags = Vec::new(); + for variant in &self.variants { + for binding in &variant.bindings { + generics_fuse(&mut flags, &binding.seen_generics); + } + } + fetch_generics(&flags, &self.ast.generics) + } + + /// Adds an `impl<>` generic parameter. + /// This can be used when the trait to be derived needs some extra generic parameters. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// let generic: syn::GenericParam = syn::parse_quote!(X: krate::AnotherTrait); + /// + /// assert_eq!( + /// s.add_impl_generic(generic) + /// .bound_impl(quote!(krate::Trait), + /// quote!{ + /// fn a() {} + /// } + /// ).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where T : krate :: Trait < X >, + /// Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn add_impl_generic(&mut self, param: GenericParam) -> &mut Self { + self.extra_impl.push(param); + self + } + + /// Add trait bounds for a trait with the given path for each type parmaeter + /// referenced in the types of non-filtered fields. + /// + /// # Caveat + /// + /// If the method contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + pub fn add_trait_bounds( + &self, + bound: &TraitBound, + where_clause: &mut Option, + mode: AddBounds, + ) { + // If we have any explicit where predicates, make sure to add them first. + if !self.extra_predicates.is_empty() { + let clause = get_or_insert_with(&mut *where_clause, || WhereClause { + where_token: Default::default(), + predicates: punctuated::Punctuated::new(), + }); + clause + .predicates + .extend(self.extra_predicates.iter().cloned()); + } + + let mut seen = HashSet::new(); + let mut pred = |ty: Type| { + if !seen.contains(&ty) { + seen.insert(ty.clone()); + + // Add a predicate. + let clause = get_or_insert_with(&mut *where_clause, || WhereClause { + where_token: Default::default(), + predicates: punctuated::Punctuated::new(), + }); + clause.predicates.push(WherePredicate::Type(PredicateType { + lifetimes: None, + bounded_ty: ty, + colon_token: Default::default(), + bounds: Some(punctuated::Pair::End(TypeParamBound::Trait(bound.clone()))) + .into_iter() + .collect(), + })); + } + }; + + for variant in &self.variants { + for binding in &variant.bindings { + match mode { + AddBounds::Both | AddBounds::Fields => { + for &seen in &binding.seen_generics { + if seen { + pred(binding.ast().ty.clone()); + break; + } + } + } + _ => {} + } + + match mode { + AddBounds::Both | AddBounds::Generics => { + for param in binding.referenced_ty_params() { + pred(Type::Path(TypePath { + qself: None, + path: (*param).clone().into(), + })); + } + } + _ => {} + } + } + } + } + + /// This method is a no-op, underscore consts are used by default now. + pub fn underscore_const(&mut self, _enabled: bool) -> &mut Self { + self + } + + /// > NOTE: This methods' features are superceded by `Structure::gen_impl`. + /// + /// Creates an `impl` block with the required generic type fields filled in + /// to implement the trait `path`. + /// + /// This method also adds where clauses to the impl requiring that all + /// referenced type parmaeters implement the trait `path`. + /// + /// # Hygiene and Paths + /// + /// This method wraps the impl block inside of a `const` (see the example + /// below). In this scope, the first segment of the passed-in path is + /// `extern crate`-ed in. If you don't want to generate that `extern crate` + /// item, use a global path. + /// + /// This means that if you are implementing `my_crate::Trait`, you simply + /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the + /// entirety of the definition, you can refer to your crate as `my_crate`. + /// + /// # Caveat + /// + /// If the method contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Panics + /// + /// Panics if the path string parameter is not a valid `TraitBound`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.bound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn bound_impl(&self, path: P, body: B) -> TokenStream { + self.impl_internal( + path.into_token_stream(), + body.into_token_stream(), + quote!(), + None, + ) + } + + /// > NOTE: This methods' features are superceded by `Structure::gen_impl`. + /// + /// Creates an `impl` block with the required generic type fields filled in + /// to implement the unsafe trait `path`. + /// + /// This method also adds where clauses to the impl requiring that all + /// referenced type parmaeters implement the trait `path`. + /// + /// # Hygiene and Paths + /// + /// This method wraps the impl block inside of a `const` (see the example + /// below). In this scope, the first segment of the passed-in path is + /// `extern crate`-ed in. If you don't want to generate that `extern crate` + /// item, use a global path. + /// + /// This means that if you are implementing `my_crate::Trait`, you simply + /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the + /// entirety of the definition, you can refer to your crate as `my_crate`. + /// + /// # Caveat + /// + /// If the method contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Panics + /// + /// Panics if the path string parameter is not a valid `TraitBound`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.unsafe_bound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// unsafe impl krate::Trait for A + /// where Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn unsafe_bound_impl(&self, path: P, body: B) -> TokenStream { + self.impl_internal( + path.into_token_stream(), + body.into_token_stream(), + quote!(unsafe), + None, + ) + } + + /// > NOTE: This methods' features are superceded by `Structure::gen_impl`. + /// + /// Creates an `impl` block with the required generic type fields filled in + /// to implement the trait `path`. + /// + /// This method will not add any where clauses to the impl. + /// + /// # Hygiene and Paths + /// + /// This method wraps the impl block inside of a `const` (see the example + /// below). In this scope, the first segment of the passed-in path is + /// `extern crate`-ed in. If you don't want to generate that `extern crate` + /// item, use a global path. + /// + /// This means that if you are implementing `my_crate::Trait`, you simply + /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the + /// entirety of the definition, you can refer to your crate as `my_crate`. + /// + /// # Panics + /// + /// Panics if the path string parameter is not a valid `TraitBound`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.unbound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + pub fn unbound_impl(&self, path: P, body: B) -> TokenStream { + self.impl_internal( + path.into_token_stream(), + body.into_token_stream(), + quote!(), + Some(AddBounds::None), + ) + } + + /// > NOTE: This methods' features are superceded by `Structure::gen_impl`. + /// + /// Creates an `impl` block with the required generic type fields filled in + /// to implement the unsafe trait `path`. + /// + /// This method will not add any where clauses to the impl. + /// + /// # Hygiene and Paths + /// + /// This method wraps the impl block inside of a `const` (see the example + /// below). In this scope, the first segment of the passed-in path is + /// `extern crate`-ed in. If you don't want to generate that `extern crate` + /// item, use a global path. + /// + /// This means that if you are implementing `my_crate::Trait`, you simply + /// write `s.bound_impl(quote!(my_crate::Trait), quote!(...))`, and for the + /// entirety of the definition, you can refer to your crate as `my_crate`. + /// + /// # Panics + /// + /// Panics if the path string parameter is not a valid `TraitBound`. + /// + /// # Example + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.unsafe_unbound_impl(quote!(krate::Trait), quote!{ + /// fn a() {} + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// unsafe impl krate::Trait for A { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + #[deprecated] + pub fn unsafe_unbound_impl(&self, path: P, body: B) -> TokenStream { + self.impl_internal( + path.into_token_stream(), + body.into_token_stream(), + quote!(unsafe), + Some(AddBounds::None), + ) + } + + fn impl_internal( + &self, + path: TokenStream, + body: TokenStream, + safety: TokenStream, + mode: Option, + ) -> TokenStream { + let mode = mode.unwrap_or(self.add_bounds); + let name = &self.ast.ident; + let mut gen_clone = self.ast.generics.clone(); + gen_clone.params.extend(self.extra_impl.iter().cloned()); + let (impl_generics, _, _) = gen_clone.split_for_impl(); + let (_, ty_generics, where_clause) = self.ast.generics.split_for_impl(); + + let bound = syn::parse2::(path) + .expect("`path` argument must be a valid rust trait bound"); + + let mut where_clause = where_clause.cloned(); + self.add_trait_bounds(&bound, &mut where_clause, mode); + + // This function is smart. If a global path is passed, no extern crate + // statement will be generated, however, a relative path will cause the + // crate which it is relative to to be imported within the current + // scope. + let mut extern_crate = quote!(); + if bound.path.leading_colon.is_none() { + if let Some(seg) = bound.path.segments.first() { + let seg = &seg.ident; + extern_crate = quote! { extern crate #seg; }; + } + } + + let generated = quote! { + #extern_crate + #safety impl #impl_generics #bound for #name #ty_generics #where_clause { + #body + } + }; + + quote! { + const _: () = { #generated }; + } + } + + /// Generate an impl block for the given struct. This impl block will + /// automatically use hygiene tricks to avoid polluting the caller's + /// namespace, and will automatically add trait bounds for generic type + /// parameters. + /// + /// # Syntax + /// + /// This function accepts its arguments as a `TokenStream`. The recommended way + /// to call this function is passing the result of invoking the `quote!` + /// macro to it. + /// + /// ```ignore + /// s.gen_impl(quote! { + /// // You can write any items which you want to import into scope here. + /// // For example, you may want to include an `extern crate` for the + /// // crate which implements your trait. These items will only be + /// // visible to the code you generate, and won't be exposed to the + /// // consuming crate + /// extern crate krate; + /// + /// // You can also add `use` statements here to bring types or traits + /// // into scope. + /// // + /// // WARNING: Try not to use common names here, because the stable + /// // version of syn does not support hygiene and you could accidentally + /// // shadow types from the caller crate. + /// use krate::Trait as MyTrait; + /// + /// // The actual impl block is a `gen impl` or `gen unsafe impl` block. + /// // You can use `@Self` to refer to the structure's type. + /// gen impl MyTrait for @Self { + /// fn f(&self) { ... } + /// } + /// }) + /// ``` + /// + /// The most common usage of this trait involves loading the crate the + /// target trait comes from with `extern crate`, and then invoking a `gen + /// impl` block. + /// + /// # Hygiene + /// + /// This method tries to handle hygiene intelligently for both stable and + /// unstable proc-macro implementations, however there are visible + /// differences. + /// + /// The output of every `gen_impl` function is wrapped in a dummy `const` + /// value, to ensure that it is given its own scope, and any values brought + /// into scope are not leaked to the calling crate. + /// + /// By default, the above invocation may generate an output like the + /// following: + /// + /// ```ignore + /// const _: () = { + /// extern crate krate; + /// use krate::Trait as MyTrait; + /// impl MyTrait for Struct where T: MyTrait { + /// fn f(&self) { ... } + /// } + /// }; + /// ``` + /// + /// ### Using the `std` crate + /// + /// If you are using `quote!()` to implement your trait, with the + /// `proc-macro2/nightly` feature, `std` isn't considered to be in scope for + /// your macro. This means that if you use types from `std` in your + /// procedural macro, you'll want to explicitly load it with an `extern + /// crate std;`. + /// + /// ### Absolute paths + /// + /// You should generally avoid using absolute paths in your generated code, + /// as they will resolve very differently when using the stable and nightly + /// versions of `proc-macro2`. Instead, load the crates you need to use + /// explictly with `extern crate` and + /// + /// # Trait Bounds + /// + /// This method will automatically add trait bounds for any type parameters + /// which are referenced within the types of non-ignored fields. + /// + /// Additional type parameters may be added with the generics syntax after + /// the `impl` keyword. + /// + /// ### Type Macro Caveat + /// + /// If the method contains any macros in type position, all parameters will + /// be considered bound. This is because we cannot determine which type + /// parameters are bound by type macros. + /// + /// # Errors + /// + /// This function will generate a `compile_error!` if additional type + /// parameters added by `impl<..>` conflict with generic type parameters on + /// the original struct. + /// + /// # Panics + /// + /// This function will panic if the input `TokenStream` is not well-formed. + /// + /// # Example Usage + /// + /// ``` + /// # use synstructure::*; + /// let di: syn::DeriveInput = syn::parse_quote! { + /// enum A { + /// B(T), + /// C(Option), + /// } + /// }; + /// let mut s = Structure::new(&di); + /// + /// s.filter_variants(|v| v.ast().ident != "B"); + /// + /// assert_eq!( + /// s.gen_impl(quote! { + /// extern crate krate; + /// gen impl krate::Trait for @Self { + /// fn a() {} + /// } + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where + /// Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// + /// // NOTE: You can also add extra generics after the impl + /// assert_eq!( + /// s.gen_impl(quote! { + /// extern crate krate; + /// gen impl krate::Trait for @Self + /// where + /// X: Send + Sync, + /// { + /// fn a() {} + /// } + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where + /// X: Send + Sync, + /// Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// }; + /// }.to_string() + /// ); + /// + /// // NOTE: you can generate multiple traits with a single call + /// assert_eq!( + /// s.gen_impl(quote! { + /// extern crate krate; + /// + /// gen impl krate::Trait for @Self { + /// fn a() {} + /// } + /// + /// gen impl krate::OtherTrait for @Self { + /// fn b() {} + /// } + /// }).to_string(), + /// quote!{ + /// const _: () = { + /// extern crate krate; + /// impl krate::Trait for A + /// where + /// Option: krate::Trait, + /// U: krate::Trait + /// { + /// fn a() {} + /// } + /// + /// impl krate::OtherTrait for A + /// where + /// Option: krate::OtherTrait, + /// U: krate::OtherTrait + /// { + /// fn b() {} + /// } + /// }; + /// }.to_string() + /// ); + /// ``` + /// + /// Use `add_bounds` to change which bounds are generated. + pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream { + Parser::parse2( + |input: ParseStream<'_>| -> Result { self.gen_impl_parse(input, true) }, + cfg, + ) + .expect("Failed to parse gen_impl") + } + + fn gen_impl_parse(&self, input: ParseStream<'_>, wrap: bool) -> Result { + fn parse_prefix(input: ParseStream<'_>) -> Result> { + if input.parse::()? != "gen" { + return Err(input.error("Expected keyword `gen`")); + } + let safety = input.parse::>()?; + let _ = input.parse::()?; + Ok(safety) + } + + let mut before = vec![]; + loop { + if parse_prefix(&input.fork()).is_ok() { + break; + } + before.push(input.parse::()?); + } + + // Parse the prefix "for real" + let safety = parse_prefix(input)?; + + // optional `<>` + let mut generics = input.parse::()?; + + // @bound + let bound = input.parse::()?; + + // `for @Self` + let _ = input.parse::()?; + let _ = input.parse::()?; + let _ = input.parse::()?; + + // optional `where ...` + generics.where_clause = input.parse()?; + + // Body of the impl + let body; + braced!(body in input); + let body = body.parse::()?; + + // Try to parse the next entry in sequence. If this fails, we'll fall + // back to just parsing the entire rest of the TokenStream. + let maybe_next_impl = self.gen_impl_parse(&input.fork(), false); + + // Eat tokens to the end. Whether or not our speculative nested parse + // succeeded, we're going to want to consume the rest of our input. + let mut after = input.parse::()?; + if let Ok(stream) = maybe_next_impl { + after = stream; + } + assert!(input.is_empty(), "Should've consumed the rest of our input"); + + /* Codegen Logic */ + let name = &self.ast.ident; + + // Add the generics from the original struct in, and then add any + // additional trait bounds which we need on the type. + if let Err(err) = merge_generics(&mut generics, &self.ast.generics) { + // Report the merge error as a `compile_error!`, as it may be + // triggerable by an end-user. + return Ok(err.to_compile_error()); + } + + self.add_trait_bounds(&bound, &mut generics.where_clause, self.add_bounds); + let (impl_generics, _, where_clause) = generics.split_for_impl(); + let (_, ty_generics, _) = self.ast.generics.split_for_impl(); + + let generated = quote! { + #(#before)* + #safety impl #impl_generics #bound for #name #ty_generics #where_clause { + #body + } + #after + }; + + if wrap { + Ok(quote! { + const _: () = { #generated }; + }) + } else { + Ok(generated) + } + } +} + +/// Dumps an unpretty version of a tokenstream. Takes any type which implements +/// `Display`. +/// +/// This is mostly useful for visualizing the output of a procedural macro, as +/// it makes it marginally more readable. It is used in the implementation of +/// `test_derive!` to unprettily print the output. +/// +/// # Stability +/// +/// The stability of the output of this function is not guaranteed. Do not +/// assert that the output of this function does not change between minor +/// versions. +/// +/// # Example +/// +/// ``` +/// # use quote::quote; +/// assert_eq!( +/// synstructure::unpretty_print(quote! { +/// const _: () = { +/// extern crate krate; +/// impl krate::Trait for A +/// where +/// Option: krate::Trait, +/// U: krate::Trait +/// { +/// fn a() {} +/// } +/// }; +/// }), +/// "const _ : ( +/// ) +/// = { +/// extern crate krate ; +/// impl < T , U > krate :: Trait for A < T , U > where Option < U > : krate :: Trait , U : krate :: Trait { +/// fn a ( +/// ) +/// { +/// } +/// } +/// } +/// ; +/// " +/// ) +/// ``` +pub fn unpretty_print(ts: T) -> String { + let mut res = String::new(); + + let raw_s = ts.to_string(); + let mut s = &raw_s[..]; + let mut indent = 0; + while let Some(i) = s.find(&['(', '{', '[', ')', '}', ']', ';'][..]) { + match &s[i..=i] { + "(" | "{" | "[" => indent += 1, + ")" | "}" | "]" => indent -= 1, + _ => {} + } + res.push_str(&s[..=i]); + res.push('\n'); + for _ in 0..indent { + res.push_str(" "); + } + s = trim_start_matches(&s[i + 1..], ' '); + } + res.push_str(s); + res +} + +/// `trim_left_matches` has been deprecated in favor of `trim_start_matches`. +/// This helper silences the warning, as we need to continue using +/// `trim_left_matches` for rust 1.15 support. +#[allow(deprecated)] +fn trim_start_matches(s: &str, c: char) -> &str { + s.trim_left_matches(c) +} + +/// Helper trait describing values which may be returned by macro implementation +/// methods used by this crate's macros. +pub trait MacroResult { + /// Convert this result into a `Result` for further processing / validation. + fn into_result(self) -> Result; + + /// Convert this result into a `proc_macro::TokenStream`, ready to return + /// from a native `proc_macro` implementation. + /// + /// If `into_result()` would return an `Err`, this method should instead + /// generate a `compile_error!` invocation to nicely report the error. + /// + /// *This method is available if `synstructure` is built with the + /// `"proc-macro"` feature.* + #[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" + ))] + fn into_stream(self) -> proc_macro::TokenStream + where + Self: Sized, + { + match self.into_result() { + Ok(ts) => ts.into(), + Err(err) => err.to_compile_error().into(), + } + } +} + +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +impl MacroResult for proc_macro::TokenStream { + fn into_result(self) -> Result { + Ok(self.into()) + } + + fn into_stream(self) -> proc_macro::TokenStream { + self + } +} + +impl MacroResult for TokenStream { + fn into_result(self) -> Result { + Ok(self) + } +} + +impl MacroResult for Result { + fn into_result(self) -> Result { + match self { + Ok(v) => v.into_result(), + Err(err) => Err(err), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Regression test for #48 + #[test] + fn test_each_enum() { + let di: syn::DeriveInput = syn::parse_quote! { + enum A { + Foo(usize, bool), + Bar(bool, usize), + Baz(usize, bool, usize), + Quux(bool, usize, bool) + } + }; + let mut s = Structure::new(&di); + + s.filter(|bi| bi.ast().ty.to_token_stream().to_string() == "bool"); + + assert_eq!( + s.each(|bi| quote!(do_something(#bi))).to_string(), + quote! { + A::Foo(_, ref __binding_1,) => { { do_something(__binding_1) } } + A::Bar(ref __binding_0, ..) => { { do_something(__binding_0) } } + A::Baz(_, ref __binding_1, ..) => { { do_something(__binding_1) } } + A::Quux(ref __binding_0, _, ref __binding_2,) => { + { + do_something(__binding_0) + } + { + do_something(__binding_2) + } + } + } + .to_string() + ); + } +} diff --git a/third-party/rust/crates/synstructure/0.13.1/src/macros.rs b/third-party/rust/crates/synstructure/0.13.1/src/macros.rs new file mode 100644 index 000000000..dc17ce3fd --- /dev/null +++ b/third-party/rust/crates/synstructure/0.13.1/src/macros.rs @@ -0,0 +1,262 @@ +//! This module provides two utility macros for testing custom derives. They can +//! be used together to eliminate some of the boilerplate required in order to +//! declare and test custom derive implementations. + +// Re-exports used by the decl_derive! and test_derive! +pub use proc_macro2::TokenStream as TokenStream2; +pub use syn::{parse2, parse_str, DeriveInput}; +pub use quote::quote; + +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +pub use proc_macro::TokenStream; +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +pub use syn::parse; + +/// The `decl_derive!` macro declares a custom derive wrapper. It will parse the +/// incoming `TokenStream` into a `synstructure::Structure` object, and pass it +/// into the inner function. +/// +/// Your inner function should take a `synstructure::Structure` by value, and +/// return a type implementing `synstructure::MacroResult`, for example: +/// +/// ``` +/// fn derive_simple(input: synstructure::Structure) -> proc_macro2::TokenStream { +/// unimplemented!() +/// } +/// +/// fn derive_result(input: synstructure::Structure) +/// -> syn::Result +/// { +/// unimplemented!() +/// } +/// ``` +/// +/// # Usage +/// +/// ### Without Attributes +/// ``` +/// fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { +/// quote::quote! { ... } +/// } +/// +/// # const _IGNORE: &'static str = stringify! { +/// decl_derive!([Interesting] => derive_interesting); +/// # }; +/// ``` +/// +/// ### With Attributes +/// ``` +/// # fn main() {} +/// fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { +/// quote::quote! { ... } +/// } +/// +/// # const _IGNORE: &'static str = stringify! { +/// decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); +/// # }; +/// ``` +/// +/// ### Decl Attributes & Doc Comments +/// ``` +/// # fn main() {} +/// fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { +/// quote::quote! { ... } +/// } +/// +/// # const _IGNORE: &'static str = stringify! { +/// decl_derive! { +/// [Interesting] => +/// #[allow(some_lint)] +/// /// Documentation Comments +/// derive_interesting +/// } +/// # }; +/// ``` +/// +/// *This macro is available if `synstructure` is built with the `"proc-macro"` +/// feature.* +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +#[macro_export] +macro_rules! decl_derive { + // XXX: Switch to using this variant everywhere? + ([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path) => { + #[proc_macro_derive($derives $($derive_t)*)] + #[allow(non_snake_case)] + $(#[$($attrs)*])* + pub fn $derives( + i: $crate::macros::TokenStream + ) -> $crate::macros::TokenStream { + match $crate::macros::parse::<$crate::macros::DeriveInput>(i) { + ::core::result::Result::Ok(p) => { + match $crate::Structure::try_new(&p) { + ::core::result::Result::Ok(s) => $crate::MacroResult::into_stream($inner(s)), + ::core::result::Result::Err(e) => { + ::core::convert::Into::into(e.to_compile_error()) + } + } + } + ::core::result::Result::Err(e) => { + ::core::convert::Into::into(e.to_compile_error()) + } + } + } + }; +} + +/// The `decl_attribute!` macro declares a custom attribute wrapper. It will +/// parse the incoming `TokenStream` into a `synstructure::Structure` object, +/// and pass it into the inner function. +/// +/// Your inner function should have the following type: +/// +/// ``` +/// fn attribute( +/// attr: proc_macro2::TokenStream, +/// structure: synstructure::Structure, +/// ) -> proc_macro2::TokenStream { +/// unimplemented!() +/// } +/// ``` +/// +/// # Usage +/// +/// ``` +/// fn attribute_interesting( +/// _attr: proc_macro2::TokenStream, +/// _structure: synstructure::Structure, +/// ) -> proc_macro2::TokenStream { +/// quote::quote! { ... } +/// } +/// +/// # const _IGNORE: &'static str = stringify! { +/// decl_attribute!([interesting] => attribute_interesting); +/// # }; +/// ``` +/// +/// *This macro is available if `synstructure` is built with the `"proc-macro"` +/// feature.* +#[cfg(all( + not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "wasi"))), + feature = "proc-macro" +))] +#[macro_export] +macro_rules! decl_attribute { + ([$attribute:ident] => $(#[$($attrs:tt)*])* $inner:path) => { + #[proc_macro_attribute] + $(#[$($attrs)*])* + pub fn $attribute( + attr: $crate::macros::TokenStream, + i: $crate::macros::TokenStream, + ) -> $crate::macros::TokenStream { + match $crate::macros::parse::<$crate::macros::DeriveInput>(i) { + ::core::result::Result::Ok(p) => match $crate::Structure::try_new(&p) { + ::core::result::Result::Ok(s) => { + $crate::MacroResult::into_stream( + $inner(::core::convert::Into::into(attr), s) + ) + } + ::core::result::Result::Err(e) => { + ::core::convert::Into::into(e.to_compile_error()) + } + }, + ::core::result::Result::Err(e) => { + ::core::convert::Into::into(e.to_compile_error()) + } + } + } + }; +} + +/// Run a test on a custom derive. This macro expands both the original struct +/// and the expansion to ensure that they compile correctly, and confirms that +/// feeding the original struct into the named derive will produce the written +/// output. +/// +/// You can add `no_build` to the end of the macro invocation to disable +/// checking that the written code compiles. This is useful in contexts where +/// the procedural macro cannot depend on the crate where it is used during +/// tests. +/// +/// # Usage +/// +/// ``` +/// fn test_derive_example(_s: synstructure::Structure) +/// -> Result +/// { +/// Ok(quote::quote! { const YOUR_OUTPUT: &'static str = "here"; }) +/// } +/// +/// fn main() { +/// synstructure::test_derive!{ +/// test_derive_example { +/// struct A; +/// } +/// expands to { +/// const YOUR_OUTPUT: &'static str = "here"; +/// } +/// } +/// } +/// ``` +#[macro_export] +macro_rules! test_derive { + ($name:path { $($i:tt)* } expands to { $($o:tt)* }) => { + { + #[allow(dead_code)] + fn ensure_compiles() { + $($i)* + $($o)* + } + + $crate::test_derive!($name { $($i)* } expands to { $($o)* } no_build); + } + }; + + ($name:path { $($i:tt)* } expands to { $($o:tt)* } no_build) => { + { + let i = $crate::macros::quote!( $($i)* ); + let parsed = $crate::macros::parse2::<$crate::macros::DeriveInput>(i) + .expect(::core::concat!( + "Failed to parse input to `#[derive(", + ::core::stringify!($name), + ")]`", + )); + + let raw_res = $name($crate::Structure::new(&parsed)); + let res = $crate::MacroResult::into_result(raw_res) + .expect(::core::concat!( + "Procedural macro failed for `#[derive(", + ::core::stringify!($name), + ")]`", + )); + + let expected_toks = $crate::macros::quote!( $($o)* ); + if <$crate::macros::TokenStream2 as ::std::string::ToString>::to_string(&res) + != <$crate::macros::TokenStream2 as ::std::string::ToString>::to_string(&expected_toks) + { + panic!("\ +test_derive failed: +expected: +``` +{} +``` + +got: +``` +{} +```\n", + $crate::unpretty_print(&expected_toks), + $crate::unpretty_print(&res), + ); + } + } + }; +} diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/.cargo_vcs_info.json b/third-party/rust/crates/zerofrom-derive/0.1.4/.cargo_vcs_info.json new file mode 100644 index 000000000..5f9dbd460 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "55cd12ebb25c6261492e1e3dfa2e6453c54dde31" + }, + "path_in_vcs": "utils/zerofrom/derive" +} \ No newline at end of file diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/BUCK b/third-party/rust/crates/zerofrom-derive/0.1.4/BUCK new file mode 100644 index 000000000..b4877c962 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/BUCK @@ -0,0 +1,17 @@ +load("@prelude//rust:cargo_package.bzl", "cargo") + +cargo.rust_library( + name = "zerofrom-derive", + srcs = glob(["src/**/*.rs"]), + crate = "zerofrom_derive", + crate_root = "src/lib.rs", + edition = "2021", + proc_macro = True, + visibility = ["PUBLIC"], + deps = [ + "//third-party/rust/crates/proc-macro2/1.0.94:proc-macro2", + "//third-party/rust/crates/quote/1.0.40:quote", + "//third-party/rust/crates/syn/2.0.100:syn", + "//third-party/rust/crates/synstructure/0.13.1:synstructure", + ], +) \ No newline at end of file diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.lock b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.lock new file mode 100644 index 000000000..dc85acde8 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.lock @@ -0,0 +1,59 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml new file mode 100644 index 000000000..f79f38652 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml @@ -0,0 +1,54 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "zerofrom-derive" +version = "0.1.4" +authors = ["Manish Goregaokar "] +description = "Custom derive for the zerofrom crate" +readme = "README.md" +keywords = [ + "zerocopy", + "serialization", + "lifetime", + "borrow", +] +categories = [ + "data-structures", + "memory-management", + "caching", + "no-std", +] +license = "Unicode-3.0" +repository = "https://github.com/unicode-org/icu4x" + +[package.metadata.workspaces] +independent = true + +[lib] +path = "src/lib.rs" +proc-macro = true + +[dependencies.proc-macro2] +version = "1.0.61" + +[dependencies.quote] +version = "1.0.28" + +[dependencies.syn] +version = "2.0.21" +features = ["fold"] + +[dependencies.synstructure] +version = "0.13.0" + +[dev-dependencies] diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml.orig b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml.orig new file mode 100644 index 000000000..3de7efbdb --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/Cargo.toml.orig @@ -0,0 +1,33 @@ +# This file is part of ICU4X. For terms of use, please see the file +# called LICENSE at the top level of the ICU4X source tree +# (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +[package] +name = "zerofrom-derive" +description = "Custom derive for the zerofrom crate" +version = "0.1.4" +authors = ["Manish Goregaokar "] +categories = ["data-structures", "memory-management", "caching", "no-std"] +keywords = ["zerocopy", "serialization", "lifetime", "borrow"] + +edition.workspace = true +license.workspace = true +repository.workspace = true + +[package.metadata.workspaces] +independent = true + +[lib] +proc-macro = true +path = "src/lib.rs" + +[dependencies] +proc-macro2 = { workspace = true } +quote = { workspace = true } +syn = { workspace = true, features = ["fold"] } +synstructure = { workspace = true } + +[dev-dependencies] +zerofrom = { path = "..", features = ["derive"]} +zerovec = { path = "../../../utils/zerovec", features = ["yoke"] } + diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/LICENSE b/third-party/rust/crates/zerofrom-derive/0.1.4/LICENSE new file mode 100644 index 000000000..c9be6012c --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/LICENSE @@ -0,0 +1,46 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2020-2024 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/README.md b/third-party/rust/crates/zerofrom-derive/0.1.4/README.md new file mode 100644 index 000000000..ad803c599 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/README.md @@ -0,0 +1,11 @@ +# zerofrom-derive [![crates.io](https://img.shields.io/crates/v/zerofrom-derive)](https://crates.io/crates/zerofrom-derive) + + + +Custom derives for `ZeroFrom` from the `zerofrom` crate. + + + +## More Information + +For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x). diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/examples/zf_derive.rs b/third-party/rust/crates/zerofrom-derive/0.1.4/examples/zf_derive.rs new file mode 100644 index 000000000..d3eb2a6fb --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/examples/zf_derive.rs @@ -0,0 +1,115 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +#![allow(unused)] + +use std::{borrow::Cow, marker::PhantomData}; +use zerofrom::ZeroFrom; +use zerovec::{maps::ZeroMapKV, ule::AsULE, VarZeroVec, ZeroMap, ZeroVec}; + +#[derive(ZeroFrom, Copy, Clone)] +pub struct IntExample { + x: u32, +} + +#[derive(ZeroFrom, Copy, Clone)] +pub struct GenericsExample { + x: u32, + y: T, +} + +#[derive(ZeroFrom, Copy, Clone)] +pub struct GenericsExampleWithDefault { + x: T, + y: U, +} + +#[derive(ZeroFrom)] +pub struct CowExample<'a> { + x: u8, + y: &'a str, + z: Cow<'a, str>, + w: Cow<'a, [u8]>, +} + +#[derive(ZeroFrom)] +pub struct ZeroVecExample<'a> { + var: VarZeroVec<'a, str>, + vec: ZeroVec<'a, u16>, +} + +#[derive(ZeroFrom)] +pub struct ZeroVecExampleWithGenerics<'a, T: AsULE> { + gen: ZeroVec<'a, T>, + vec: ZeroVec<'a, u16>, + bare: T, +} + +#[derive(ZeroFrom)] +pub struct HasTuples<'data> { + pub bar: (&'data str, &'data str), +} + +pub fn assert_zf_tuples<'b>(x: &'b HasTuples) -> HasTuples<'b> { + HasTuples::zero_from(x) +} +pub fn assert_zf_generics<'a, 'b>( + x: &'b ZeroVecExampleWithGenerics<'a, u8>, +) -> ZeroVecExampleWithGenerics<'b, u8> { + ZeroVecExampleWithGenerics::<'b, u8>::zero_from(x) +} + +#[derive(ZeroFrom)] +pub struct ZeroMapGenericExample<'a, T: for<'b> ZeroMapKV<'b> + ?Sized> { + map: ZeroMap<'a, str, T>, +} + +pub fn assert_zf_map<'b>(x: &'b ZeroMapGenericExample) -> ZeroMapGenericExample<'b, str> { + ZeroMapGenericExample::zero_from(x) +} + +#[derive(Clone, ZeroFrom)] +pub struct CloningZF1 { + #[zerofrom(clone)] // Vec is not ZeroFrom, so it needs to be cloned + vec: Vec, +} + +#[derive(Clone, ZeroFrom)] +pub struct CloningZF2<'data> { + #[zerofrom(clone)] // Cow is ZeroFrom, but we force a clone + cow: Cow<'data, str>, +} + +#[derive(ZeroFrom)] +pub enum CloningZF3<'data> { + Cow(#[zerofrom(clone)] Cow<'data, str>), +} + +#[derive(ZeroFrom)] +#[zerofrom(may_borrow(T, Q))] // instead of treating T as a copy type, we want to allow zerofromming T too +pub struct GenericsThatAreAlsoZf { + x: T, + y: Option, + ignored: PhantomData, + q: Q, +} + +pub fn assert_zf_generics_may_borrow<'a, 'b>( + x: &'b GenericsThatAreAlsoZf<&'a str, usize, str>, +) -> GenericsThatAreAlsoZf<&'b str, usize, str> { + GenericsThatAreAlsoZf::<&'b str, usize, str>::zero_from(x) +} + +#[derive(ZeroFrom)] +pub struct UsesGenericsThatAreAlsoZf<'a> { + x: GenericsThatAreAlsoZf<&'a str, usize, str>, +} + +// Ensure it works with invariant types too +#[derive(ZeroFrom)] +pub struct UsesGenericsThatAreAlsoZfWithMap<'a> { + x: GenericsThatAreAlsoZf, usize, str>, +} + +fn main() {} diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/src/lib.rs b/third-party/rust/crates/zerofrom-derive/0.1.4/src/lib.rs new file mode 100644 index 000000000..67d40851e --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/src/lib.rs @@ -0,0 +1,308 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +//! Custom derives for `ZeroFrom` from the `zerofrom` crate. + +// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations +#![cfg_attr( + not(test), + deny( + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::exhaustive_structs, + clippy::exhaustive_enums, + missing_debug_implementations, + ) +)] + +use core::mem; +use proc_macro::TokenStream; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::quote; +use std::collections::{HashMap, HashSet}; +use syn::fold::{self, Fold}; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use syn::{ + parse_macro_input, parse_quote, DeriveInput, Ident, Lifetime, MetaList, Token, + TraitBoundModifier, Type, TypeParamBound, TypePath, WherePredicate, +}; +use synstructure::Structure; +mod visitor; + +/// Custom derive for `zerofrom::ZeroFrom`, +/// +/// This implements `ZeroFrom for Ty` for types +/// without a lifetime parameter, and `ZeroFrom> for Ty<'static>` +/// for types with a lifetime parameter. +/// +/// Apply the `#[zerofrom(clone)]` attribute to a field if it doesn't implement +/// Copy or ZeroFrom; this data will be cloned when the struct is zero_from'ed. +/// +/// Apply the `#[zerofrom(maybe_borrow(T, U, V))]` attribute to the struct to indicate +/// that certain type parameters may themselves contain borrows (by default +/// the derives assume that type parameters perform no borrows and can be copied or cloned). +/// +/// In rust versions where [this issue](https://github.com/rust-lang/rust/issues/114393) is fixed, +/// `#[zerofrom(may_borrow)]` can be applied directly to type parameters. +#[proc_macro_derive(ZeroFrom, attributes(zerofrom))] +pub fn zf_derive(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + TokenStream::from(zf_derive_impl(&input)) +} + +fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool { + attrs.iter().any(|a| { + if let Ok(i) = a.parse_args::() { + if i == name { + return true; + } + } + false + }) +} + +// Collects all idents from #[zerofrom(may_borrow(A, B, C, D))] +// needed since #[zerofrom(may_borrow)] doesn't work yet +// (https://github.com/rust-lang/rust/issues/114393) +fn get_may_borrow_attr(attrs: &[syn::Attribute]) -> Result, Span> { + let mut params = HashSet::new(); + for attr in attrs { + if let Ok(list) = attr.parse_args::() { + if list.path.is_ident("may_borrow") { + if let Ok(list) = + list.parse_args_with(Punctuated::::parse_terminated) + { + params.extend(list) + } else { + return Err(attr.span()); + } + } + } + } + Ok(params) +} + +fn zf_derive_impl(input: &DeriveInput) -> TokenStream2 { + let mut tybounds = input + .generics + .type_params() + .map(|ty| { + // Strip out param defaults, we don't need them in the impl + let mut ty = ty.clone(); + ty.eq_token = None; + ty.default = None; + ty + }) + .collect::>(); + let typarams = tybounds + .iter() + .map(|ty| ty.ident.clone()) + .collect::>(); + let lts = input.generics.lifetimes().count(); + let name = &input.ident; + let structure = Structure::new(input); + + let may_borrow_attrs = match get_may_borrow_attr(&input.attrs) { + Ok(mb) => mb, + Err(span) => { + return syn::Error::new( + span, + "#[zerofrom(may_borrow)] on the struct takes in a comma separated list of type parameters, like so: `#[zerofrom(may_borrow(A, B, C, D)]`", + ).to_compile_error(); + } + }; + + // This contains every generic type introduced in this code. + // If the gneeric type is may_borrow, this additionally contains the identifier corresponding to + // a newly introduced mirror type parameter that we are borrowing from, similar to C in the original trait. + // For convenience, we are calling these "C types" + let generics_env: HashMap> = tybounds + .iter_mut() + .map(|param| { + // First one doesn't work yet https://github.com/rust-lang/rust/issues/114393 + let maybe_new_param = if has_attr(¶m.attrs, "may_borrow") + || may_borrow_attrs.contains(¶m.ident) + { + // Remove `?Sized`` bound because we need a param to be Sized in order to take a ZeroFrom of it. + // This only applies to fields marked as `may_borrow`. + let mut bounds = core::mem::take(&mut param.bounds); + while let Some(bound_pair) = bounds.pop() { + let bound = bound_pair.into_value(); + if let TypeParamBound::Trait(ref trait_bound) = bound { + if trait_bound.path.get_ident().map(|ident| ident == "Sized") == Some(true) + && matches!(trait_bound.modifier, TraitBoundModifier::Maybe(_)) + { + continue; + } + } + param.bounds.push(bound); + } + Some(Ident::new( + &format!("{}ZFParamC", param.ident), + param.ident.span(), + )) + } else { + None + }; + (param.ident.clone(), maybe_new_param) + }) + .collect(); + + // Do any of the generics potentially borrow? + let generics_may_borrow = generics_env.values().any(|x| x.is_some()); + + if lts == 0 && !generics_may_borrow { + let has_clone = structure + .variants() + .iter() + .flat_map(|variant| variant.bindings().iter()) + .any(|binding| has_attr(&binding.ast().attrs, "clone")); + let (clone, clone_trait) = if has_clone { + (quote!(this.clone()), quote!(Clone)) + } else { + (quote!(*this), quote!(Copy)) + }; + let bounds: Vec = typarams + .iter() + .map(|ty| parse_quote!(#ty: #clone_trait + 'static)) + .collect(); + quote! { + impl<'zf, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#(#typarams),*>> for #name<#(#typarams),*> where #(#bounds),* { + fn zero_from(this: &'zf Self) -> Self { + #clone + } + } + } + } else { + if lts > 1 { + return syn::Error::new( + input.generics.span(), + "derive(ZeroFrom) cannot have multiple lifetime parameters", + ) + .to_compile_error(); + } + + let mut zf_bounds: Vec = vec![]; + let body = structure.each_variant(|vi| { + vi.construct(|f, i| { + let binding = format!("__binding_{i}"); + let field = Ident::new(&binding, Span::call_site()); + + if has_attr(&f.attrs, "clone") { + quote! { + #field.clone() + } + } else { + // the field type + let fty = replace_lifetime(&f.ty, custom_lt("'zf")); + // the corresponding lifetimey type we are borrowing from (effectively, the C type) + let lifetime_ty = + replace_lifetime_and_type(&f.ty, custom_lt("'zf_inner"), &generics_env); + + let (has_ty, has_lt) = visitor::check_type_for_parameters(&f.ty, &generics_env); + if has_ty { + // For types without type parameters, the compiler can figure out that the field implements + // ZeroFrom on its own. However, if there are type parameters, there may be complex preconditions + // to `FieldTy: ZeroFrom` that need to be satisfied. We get them to be satisfied by requiring + // `FieldTy<'zf>: ZeroFrom<'zf, FieldTy<'zf_inner>>` + if has_lt { + zf_bounds + .push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #lifetime_ty>)); + } else { + zf_bounds.push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #fty>)); + } + } + if has_ty || has_lt { + // By doing this we essentially require ZF to be implemented + // on all fields + quote! { + <#fty as zerofrom::ZeroFrom<'zf, #lifetime_ty>>::zero_from(#field) + } + } else { + // No lifetimes, so we can just copy + quote! { *#field } + } + } + }) + }); + // Due to the possibility of generics_may_borrow, we might reach here with no lifetimes on self, + // don't accidentally feed them to self later + let (maybe_zf_lifetime, maybe_zf_inner_lifetime) = if lts == 0 { + (quote!(), quote!()) + } else { + (quote!('zf,), quote!('zf_inner,)) + }; + + // Array of C types. Only different if generics are allowed to borrow + let mut typarams_c = typarams.clone(); + + if generics_may_borrow { + for typaram_c in &mut typarams_c { + if let Some(Some(replacement)) = generics_env.get(typaram_c) { + // we use mem::replace here so we can be really clear about the C vs the T type + let typaram_t = mem::replace(typaram_c, replacement.clone()); + zf_bounds + .push(parse_quote!(#typaram_c: zerofrom::ZeroFrom<'zf_inner, #typaram_t>)); + tybounds.push(parse_quote!(#typaram_c)); + } + } + } + + quote! { + impl<'zf, 'zf_inner, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#maybe_zf_inner_lifetime #(#typarams_c),*>> for #name<#maybe_zf_lifetime #(#typarams),*> + where + #(#zf_bounds,)* { + fn zero_from(this: &'zf #name<#maybe_zf_inner_lifetime #(#typarams_c),*>) -> Self { + match *this { #body } + } + } + } + } +} + +fn custom_lt(s: &str) -> Lifetime { + Lifetime::new(s, Span::call_site()) +} + +/// Replace all lifetimes in a type with a specified one +fn replace_lifetime(x: &Type, lt: Lifetime) -> Type { + struct ReplaceLifetime(Lifetime); + + impl Fold for ReplaceLifetime { + fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime { + self.0.clone() + } + } + ReplaceLifetime(lt).fold_type(x.clone()) +} + +/// Replace all lifetimes in a type with a specified one, AND replace all types that have a corresponding C type +/// with the C type +fn replace_lifetime_and_type( + x: &Type, + lt: Lifetime, + generics_env: &HashMap>, +) -> Type { + struct ReplaceLifetimeAndTy<'a>(Lifetime, &'a HashMap>); + + impl Fold for ReplaceLifetimeAndTy<'_> { + fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime { + self.0.clone() + } + fn fold_type_path(&mut self, i: TypePath) -> TypePath { + if i.qself.is_none() { + if let Some(ident) = i.path.get_ident() { + if let Some(Some(replacement)) = self.1.get(ident) { + return parse_quote!(#replacement); + } + } + } + fold::fold_type_path(self, i) + } + } + ReplaceLifetimeAndTy(lt, generics_env).fold_type(x.clone()) +} diff --git a/third-party/rust/crates/zerofrom-derive/0.1.4/src/visitor.rs b/third-party/rust/crates/zerofrom-derive/0.1.4/src/visitor.rs new file mode 100644 index 000000000..4204b7c68 --- /dev/null +++ b/third-party/rust/crates/zerofrom-derive/0.1.4/src/visitor.rs @@ -0,0 +1,120 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +//! Visitor for determining whether a type has type and non-static lifetime parameters +//! (duplicated in yoke/derive/src/visitor.rs) + +use std::collections::HashMap; +use syn::visit::{visit_lifetime, visit_type, visit_type_path, Visit}; +use syn::{Ident, Lifetime, Type, TypePath}; + +struct TypeVisitor<'a> { + /// The type parameters in scope + typarams: &'a HashMap>, + /// Whether we found a type parameter + found_typarams: bool, + /// Whether we found a non-'static lifetime parameter + found_lifetimes: bool, +} + +impl<'a, 'ast> Visit<'ast> for TypeVisitor<'a> { + fn visit_lifetime(&mut self, lt: &'ast Lifetime) { + if lt.ident != "static" { + self.found_lifetimes = true; + } + visit_lifetime(self, lt) + } + fn visit_type_path(&mut self, ty: &'ast TypePath) { + // We only need to check ty.path.get_ident() and not ty.qself or any + // generics in ty.path because the visitor will eventually visit those + // types on its own + if let Some(ident) = ty.path.get_ident() { + if let Some(maybe_borrowed) = self.typarams.get(ident) { + self.found_typarams = true; + if maybe_borrowed.is_some() { + self.found_lifetimes = true; + } + } + } + + visit_type_path(self, ty) + } +} + +/// Checks if a type has type or lifetime parameters, given the local context of +/// named type parameters. Returns (has_type_params, has_lifetime_params) +pub fn check_type_for_parameters( + ty: &Type, + typarams: &HashMap>, +) -> (bool, bool) { + let mut visit = TypeVisitor { + typarams, + found_typarams: false, + found_lifetimes: false, + }; + visit_type(&mut visit, ty); + + (visit.found_typarams, visit.found_lifetimes) +} + +#[cfg(test)] +mod tests { + use proc_macro2::Span; + use std::collections::HashMap; + use syn::{parse_quote, Ident}; + + use super::check_type_for_parameters; + fn make_typarams(params: &[&str]) -> HashMap> { + params + .iter() + .map(|x| (Ident::new(x, Span::call_site()), None)) + .collect() + } + + #[test] + fn test_simple_type() { + let environment = make_typarams(&["T", "U", "V"]); + + let ty = parse_quote!(Foo<'a, T>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(Foo); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(Foo<'static, T>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(Foo<'a>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (false, true)); + + let ty = parse_quote!(Foo<'a, Bar, Baz<(V, u8)>>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(Foo<'a, W>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (false, true)); + } + + #[test] + fn test_assoc_types() { + let environment = make_typarams(&["T"]); + + let ty = parse_quote!(>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + } +} diff --git a/third-party/rust/crates/zerofrom/0.1.4/.cargo_vcs_info.json b/third-party/rust/crates/zerofrom/0.1.4/.cargo_vcs_info.json new file mode 100644 index 000000000..fd383a295 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "55cd12ebb25c6261492e1e3dfa2e6453c54dde31" + }, + "path_in_vcs": "utils/zerofrom" +} \ No newline at end of file diff --git a/third-party/rust/crates/zerofrom/0.1.4/BUCK b/third-party/rust/crates/zerofrom/0.1.4/BUCK new file mode 100644 index 000000000..5a6dd131a --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/BUCK @@ -0,0 +1,15 @@ +load("@prelude//rust:cargo_package.bzl", "cargo") + +cargo.rust_library( + name = "zerofrom", + srcs = glob(["src/**/*.rs"]), + crate = "zerofrom", + crate_root = "src/lib.rs", + edition = "2021", + features = [ + "alloc", + "derive", + ], + visibility = ["PUBLIC"], + deps = ["//third-party/rust/crates/zerofrom-derive/0.1.4:zerofrom-derive"], +) \ No newline at end of file diff --git a/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml b/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml new file mode 100644 index 000000000..0426ad333 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml @@ -0,0 +1,58 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.67" +name = "zerofrom" +version = "0.1.4" +authors = ["Manish Goregaokar "] +include = [ + "data/**/*", + "src/**/*", + "examples/**/*", + "benches/**/*", + "tests/**/*", + "Cargo.toml", + "LICENSE", + "README.md", +] +description = "ZeroFrom trait for constructing" +readme = "README.md" +keywords = [ + "zerocopy", + "serialization", + "lifetime", + "borrow", +] +categories = [ + "data-structures", + "caching", + "no-std", +] +license = "Unicode-3.0" +repository = "https://github.com/unicode-org/icu4x" + +[package.metadata.docs.rs] +all-features = true + +[package.metadata.workspaces] +independent = true + +[dependencies.zerofrom-derive] +version = "0.1.3" +optional = true +default-features = false + +[features] +alloc = [] +default = ["alloc"] +derive = ["dep:zerofrom-derive"] diff --git a/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml.orig b/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml.orig new file mode 100644 index 000000000..3976be311 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/Cargo.toml.orig @@ -0,0 +1,31 @@ +# This file is part of ICU4X. For terms of use, please see the file +# called LICENSE at the top level of the ICU4X source tree +# (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +[package] +name = "zerofrom" +description = "ZeroFrom trait for constructing" +version = "0.1.4" +authors = ["Manish Goregaokar "] +categories = ["data-structures", "caching", "no-std"] +keywords = ["zerocopy", "serialization", "lifetime", "borrow"] + +edition.workspace = true +include.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[package.metadata.workspaces] +independent = true + +[package.metadata.docs.rs] +all-features = true + +[features] +alloc = [] +derive = ["dep:zerofrom-derive"] +default = ["alloc"] + +[dependencies] +zerofrom-derive = { workspace = true, optional = true} diff --git a/third-party/rust/crates/zerofrom/0.1.4/LICENSE b/third-party/rust/crates/zerofrom/0.1.4/LICENSE new file mode 100644 index 000000000..c9be6012c --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/LICENSE @@ -0,0 +1,46 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2020-2024 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + +— + +Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. +ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. diff --git a/third-party/rust/crates/zerofrom/0.1.4/README.md b/third-party/rust/crates/zerofrom/0.1.4/README.md new file mode 100644 index 000000000..7f171afa0 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/README.md @@ -0,0 +1,13 @@ +# zerofrom [![crates.io](https://img.shields.io/crates/v/zerofrom)](https://crates.io/crates/zerofrom) + + + +This crate provides [`ZeroFrom`], a trait for converting types in a zero-copy way. + +See the documentation of [`ZeroFrom`] for more details. + + + +## More Information + +For more information on development, authorship, contributing etc. please visit [`ICU4X home page`](https://github.com/unicode-org/icu4x). diff --git a/third-party/rust/crates/zerofrom/0.1.4/src/lib.rs b/third-party/rust/crates/zerofrom/0.1.4/src/lib.rs new file mode 100644 index 000000000..88ce8f614 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/src/lib.rs @@ -0,0 +1,36 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +//! This crate provides [`ZeroFrom`], a trait for converting types in a zero-copy way. +//! +//! See the documentation of [`ZeroFrom`] for more details. + +// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations +#![cfg_attr(not(test), no_std)] +#![cfg_attr( + not(test), + deny( + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::exhaustive_structs, + clippy::exhaustive_enums, + missing_debug_implementations, + ) +)] +// The lifetimes here are important for safety and explicitly writing +// them out is good even when redundant +#![allow(clippy::needless_lifetimes)] + +#[cfg(feature = "alloc")] +extern crate alloc; + +mod macro_impls; +mod zero_from; + +#[cfg(feature = "derive")] +pub use zerofrom_derive::ZeroFrom; + +pub use crate::zero_from::ZeroFrom; diff --git a/third-party/rust/crates/zerofrom/0.1.4/src/macro_impls.rs b/third-party/rust/crates/zerofrom/0.1.4/src/macro_impls.rs new file mode 100644 index 000000000..3bef457e1 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/src/macro_impls.rs @@ -0,0 +1,145 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +// In this case consistency between impls is more important +// than using pointer casts +#![allow(clippy::transmute_ptr_to_ptr)] + +use crate::ZeroFrom; + +macro_rules! impl_copy_type { + ($ty:ident) => { + impl<'a> ZeroFrom<'a, $ty> for $ty { + #[inline] + fn zero_from(this: &'a Self) -> Self { + // Essentially only works when the struct is fully Copy + *this + } + } + }; +} + +impl_copy_type!(u8); +impl_copy_type!(u16); +impl_copy_type!(u32); +impl_copy_type!(u64); +impl_copy_type!(u128); +impl_copy_type!(usize); +impl_copy_type!(i8); +impl_copy_type!(i16); +impl_copy_type!(i32); +impl_copy_type!(i64); +impl_copy_type!(i128); +impl_copy_type!(isize); +impl_copy_type!(char); +impl_copy_type!(bool); + +// This can be cleaned up once `[T; N]`::each_ref() is stabilized +// https://github.com/rust-lang/rust/issues/76118 +macro_rules! array_zf_impl { + ($n:expr; $($i:expr),+) => { + impl<'a, C, T: ZeroFrom<'a, C>> ZeroFrom<'a, [C; $n]> for [T; $n] { + fn zero_from(this: &'a [C; $n]) -> Self { + [ + $( + >::zero_from(&this[$i]) + ),+ + + ] + } + } + } +} + +array_zf_impl!(1; 0); +array_zf_impl!(2; 0, 1); +array_zf_impl!(3; 0, 1, 2); +array_zf_impl!(4; 0, 1, 2, 3); +array_zf_impl!(5; 0, 1, 2, 3, 4); +array_zf_impl!(6; 0, 1, 2, 3, 4, 5); +array_zf_impl!(7; 0, 1, 2, 3, 4, 5, 6); +array_zf_impl!(8; 0, 1, 2, 3, 4, 5, 6, 7); +array_zf_impl!(9; 0, 1, 2, 3, 4, 5, 6, 7, 8); +array_zf_impl!(10; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); +array_zf_impl!(11; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); +array_zf_impl!(12; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); +array_zf_impl!(13; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); +array_zf_impl!(14; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); +array_zf_impl!(15; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); +array_zf_impl!(16; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + +macro_rules! tuple_zf_impl { + ($(($c:ident, $t:ident, $i:tt)),+) => { + impl<'zf, $($c, $t: ZeroFrom<'zf, $c>),+> ZeroFrom<'zf, ($($c),+)> + for ($($t),+) + { + fn zero_from(other: &'zf ($($c),+)) -> Self { + ( + $(<$t as ZeroFrom<$c>>::zero_from(&other.$i)),+ + ) + } + } + }; +} + +tuple_zf_impl!((C1, T1, 0), (C2, T2, 1)); +tuple_zf_impl!((C1, T1, 0), (C2, T2, 1), (C3, T3, 2)); +tuple_zf_impl!((C1, T1, 0), (C2, T2, 1), (C3, T3, 2), (C4, T4, 3)); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4) +); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4), + (C6, T6, 5) +); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4), + (C6, T6, 5), + (C7, T7, 6) +); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4), + (C6, T6, 5), + (C7, T7, 6), + (C8, T8, 7) +); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4), + (C6, T6, 5), + (C7, T7, 6), + (C8, T8, 7), + (C9, T9, 8) +); +tuple_zf_impl!( + (C1, T1, 0), + (C2, T2, 1), + (C3, T3, 2), + (C4, T4, 3), + (C5, T5, 4), + (C6, T6, 5), + (C7, T7, 6), + (C8, T8, 7), + (C9, T9, 8), + (C10, T10, 9) +); diff --git a/third-party/rust/crates/zerofrom/0.1.4/src/zero_from.rs b/third-party/rust/crates/zerofrom/0.1.4/src/zero_from.rs new file mode 100644 index 000000000..626cfc9f8 --- /dev/null +++ b/third-party/rust/crates/zerofrom/0.1.4/src/zero_from.rs @@ -0,0 +1,136 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +use core::marker::PhantomData; + +#[cfg(feature = "alloc")] +use alloc::borrow::{Cow, ToOwned}; +#[cfg(feature = "alloc")] +use alloc::string::String; + +/// Trait for types that can be created from a reference to a different type `C` with no allocations, +/// i.e. a zero-copy (zero-alloc) version of "From" +/// +/// A type can be the `ZeroFrom` target of multiple other types. +/// +/// The intention is for `ZeroFrom` to produce a struct from a other with as little work as +/// possible. Although it is technically possible to implement `ZeroFrom` without being +/// zero-copy (using heap allocations), doing so defeats the purpose of `ZeroFrom`. +/// +/// For example, `impl ZeroFrom for Cow` should return a `Cow::Borrowed` pointing at +/// data in the other type `C`, even if the other type is itself fully owned. +/// +/// One can use the [`#[derive(ZeroFrom)]`](zerofrom_derive::ZeroFrom) custom derive to automatically +/// implement this trait. +/// +/// # Examples +/// +/// Implementing `ZeroFrom` on a custom data struct: +/// +/// ``` +/// use std::borrow::Cow; +/// use zerofrom::ZeroFrom; +/// +/// struct MyStruct<'data> { +/// message: Cow<'data, str>, +/// } +/// +/// // Reference from a borrowed version of self +/// impl<'zf> ZeroFrom<'zf, MyStruct<'_>> for MyStruct<'zf> { +/// fn zero_from(other: &'zf MyStruct<'_>) -> Self { +/// MyStruct { +/// message: Cow::Borrowed(&other.message), +/// } +/// } +/// } +/// +/// // Reference from a string slice directly +/// impl<'zf> ZeroFrom<'zf, str> for MyStruct<'zf> { +/// fn zero_from(other: &'zf str) -> Self { +/// MyStruct { +/// message: Cow::Borrowed(other), +/// } +/// } +/// } +/// ``` +pub trait ZeroFrom<'zf, C: ?Sized>: 'zf { + /// Clone the other `C` into a struct that may retain references into `C`. + fn zero_from(other: &'zf C) -> Self; +} + +// Note: The following could be blanket implementations, but that would require constraining the +// blanket `T` on `T: 'static`, which may not be desirable for all downstream users who may wish +// to customize their `ZeroFrom` impl. The blanket implementation may be safe once Rust has +// specialization. + +#[cfg(feature = "alloc")] +impl<'zf> ZeroFrom<'zf, str> for Cow<'zf, str> { + #[inline] + fn zero_from(other: &'zf str) -> Self { + Cow::Borrowed(other) + } +} + +#[cfg(feature = "alloc")] +impl<'zf> ZeroFrom<'zf, String> for Cow<'zf, str> { + #[inline] + fn zero_from(other: &'zf String) -> Self { + Cow::Borrowed(other) + } +} + +impl<'zf> ZeroFrom<'zf, str> for &'zf str { + #[inline] + fn zero_from(other: &'zf str) -> Self { + other + } +} + +#[cfg(feature = "alloc")] +impl<'zf> ZeroFrom<'zf, String> for &'zf str { + #[inline] + fn zero_from(other: &'zf String) -> Self { + other + } +} + +impl<'zf, C, T: ZeroFrom<'zf, C>> ZeroFrom<'zf, Option> for Option { + fn zero_from(other: &'zf Option) -> Self { + other.as_ref().map(|c| >::zero_from(c)) + } +} + +// These duplicate the functionality from above and aren't quite necessary due +// to deref coercions, however for the custom derive to work, there always needs +// to be `impl ZeroFrom for T`, otherwise it may fail to perform the necessary +// type inference. Deref coercions do not typically work when sufficient generics +// or inference are involved, and the proc macro does not necessarily have +// enough type information to figure this out on its own. +#[cfg(feature = "alloc")] +impl<'zf, B: ToOwned + ?Sized> ZeroFrom<'zf, Cow<'_, B>> for Cow<'zf, B> { + #[inline] + fn zero_from(other: &'zf Cow<'_, B>) -> Self { + Cow::Borrowed(other) + } +} + +impl<'zf, T: ?Sized> ZeroFrom<'zf, &'_ T> for &'zf T { + #[inline] + fn zero_from(other: &'zf &'_ T) -> &'zf T { + other + } +} + +impl<'zf, T> ZeroFrom<'zf, [T]> for &'zf [T] { + #[inline] + fn zero_from(other: &'zf [T]) -> &'zf [T] { + other + } +} + +impl<'zf, T: ?Sized + 'zf> ZeroFrom<'zf, PhantomData> for PhantomData { + fn zero_from(other: &'zf PhantomData) -> Self { + *other + } +}