Bug 1961030 - build(rust): shim-upgrade strum 0.26.3 → 0.27.1 r=supply-chain-reviewers,glandium

Differential Revision: https://phabricator.services.mozilla.com/D245813
This commit is contained in:
Erich Gubler
2025-04-17 17:50:35 +00:00
parent 4e8ca4d873
commit 8f4384a847
30 changed files with 594 additions and 227 deletions

25
Cargo.lock generated
View File

@@ -4514,7 +4514,7 @@ dependencies = [
"rustc-hash 1.999.999", "rustc-hash 1.999.999",
"serde", "serde",
"spirv", "spirv",
"strum", "strum 0.26.999",
"thiserror 2.0.9", "thiserror 2.0.9",
"unicode-ident", "unicode-ident",
] ]
@@ -4550,7 +4550,7 @@ dependencies = [
"env_logger", "env_logger",
"log", "log",
"qlog", "qlog",
"strum", "strum 0.26.999",
"windows", "windows",
] ]
@@ -4567,7 +4567,7 @@ dependencies = [
"semver", "semver",
"serde", "serde",
"serde_derive", "serde_derive",
"strum", "strum 0.26.999",
"toml", "toml",
] ]
@@ -4584,7 +4584,7 @@ dependencies = [
"neqo-transport", "neqo-transport",
"qlog", "qlog",
"sfv", "sfv",
"strum", "strum 0.26.999",
"url", "url",
] ]
@@ -4615,7 +4615,7 @@ dependencies = [
"qlog", "qlog",
"smallvec", "smallvec",
"static_assertions", "static_assertions",
"strum", "strum 0.26.999",
] ]
[[package]] [[package]]
@@ -6187,18 +6187,25 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "strum" name = "strum"
version = "0.26.3" version = "0.26.999"
dependencies = [
"strum 0.27.1",
]
[[package]]
name = "strum"
version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" checksum = "f64def088c51c9510a8579e3c5d67c65349dcf755e5479ad3d010aa6454e2c32"
dependencies = [ dependencies = [
"strum_macros", "strum_macros",
] ]
[[package]] [[package]]
name = "strum_macros" name = "strum_macros"
version = "0.26.4" version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" checksum = "c77a8c5abcaf0f9ce05d62342b7d298c346515365c36b673df4ebe3ced01fde8"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",

View File

@@ -216,6 +216,9 @@ rusqlite = { path = "build/rust/rusqlite" }
# Patch `ron` 0.9.* to 0.10. # Patch `ron` 0.9.* to 0.10.
ron = { path = "build/rust/ron" } ron = { path = "build/rust/ron" }
# Patch `strum` 0.26.* to 0.27.
strum = { path = "build/rust/strum" }
# Overrides to allow easier use of common internal crates. # Overrides to allow easier use of common internal crates.
moz_asserts = { path = "mozglue/static/rust/moz_asserts" } moz_asserts = { path = "mozglue/static/rust/moz_asserts" }

View File

@@ -0,0 +1,17 @@
[package]
name = "strum"
version = "0.26.999"
edition = "2018"
license = "MIT OR Apache-2.0"
[lib]
path = "lib.rs"
[dependencies.strum]
version = "0.27.1"
default-features = false
[features]
default = ["strum/default"]
derive = ["strum/derive"]
std = ["strum/std"]

5
build/rust/strum/lib.rs Normal file
View File

@@ -0,0 +1,5 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
pub use strum::*;

View File

@@ -5009,11 +5009,21 @@ who = "Teodor Tanasoaia <ttanasoaia@mozilla.com>"
criteria = "safe-to-deploy" criteria = "safe-to-deploy"
delta = "0.25.0 -> 0.26.3" delta = "0.25.0 -> 0.26.3"
[[audits.strum]]
who = "Erich Gubler <erichdongubler@gmail.com>"
criteria = "safe-to-deploy"
delta = "0.26.3 -> 0.27.1"
[[audits.strum_macros]] [[audits.strum_macros]]
who = "Teodor Tanasoaia <ttanasoaia@mozilla.com>" who = "Teodor Tanasoaia <ttanasoaia@mozilla.com>"
criteria = "safe-to-deploy" criteria = "safe-to-deploy"
delta = "0.25.3 -> 0.26.4" delta = "0.25.3 -> 0.26.4"
[[audits.strum_macros]]
who = "Erich Gubler <erichdongubler@gmail.com>"
criteria = "safe-to-deploy"
delta = "0.26.4 -> 0.27.1"
[[audits.subtle]] [[audits.subtle]]
who = "Simon Friedberger <simon@mozilla.com>" who = "Simon Friedberger <simon@mozilla.com>"
criteria = "safe-to-deploy" criteria = "safe-to-deploy"

View File

@@ -1 +1 @@
{"files":{"Cargo.toml":"d42134f7fdb99557a91eb2baf346dceb46e50d09edf17fe1da588b6856a93e54","LICENSE":"8bce3b45e49ecd1461f223b46de133d8f62cd39f745cfdaf81bee554b908bd42","README.md":"df67b984209ce474de5d60994983f6d2db0ac3b73bcfc2b1329871b0035c57e6","src/additional_attributes.rs":"ed42563ee66b53c676b14bb499b5f9e593e377574913dac78fcdf0be0a615786","src/lib.rs":"947be8ffe7935dd2ae47251d50c478d692354385ea26ffb1fba1920b5c634133"},"package":"8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"} {"files":{"Cargo.toml":"c126f92193c89277b2cd5e9c796dac8ba2f59eff550a3720b26af9504ae4b592","LICENSE":"8bce3b45e49ecd1461f223b46de133d8f62cd39f745cfdaf81bee554b908bd42","README.md":"fbde582a544c0f2a60eb2b274ef60bbab5cf6f527e4dba0170e440898a8e10c5","src/additional_attributes.rs":"c2ec028d16a4f50286f54daed2f3b2ad8192fb2f7d791a3c0db68210a32a7603","src/lib.rs":"b41deffb2a43eb991ebc13f3a3912accc7a1e5772791b8c347ba3453d74f2157"},"package":"f64def088c51c9510a8579e3c5d67c65349dcf755e5479ad3d010aa6454e2c32"}

View File

@@ -10,15 +10,11 @@
# See Cargo.toml.orig for the original contents. # See Cargo.toml.orig for the original contents.
[package] [package]
edition = "2018" edition = "2021"
rust-version = "1.66.1"
name = "strum" name = "strum"
version = "0.26.3" version = "0.27.1"
authors = ["Peter Glotfelty <peter.glotfelty@microsoft.com>"] authors = ["Peter Glotfelty <peter.glotfelty@microsoft.com>"]
build = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Helpful macros for working with enums and strings" description = "Helpful macros for working with enums and strings"
homepage = "https://github.com/Peternator7/strum" homepage = "https://github.com/Peternator7/strum"
documentation = "https://docs.rs/strum" documentation = "https://docs.rs/strum"
@@ -43,21 +39,16 @@ rustdoc-args = [
"docsrs", "docsrs",
] ]
[lib]
name = "strum"
path = "src/lib.rs"
[dependencies.phf] [dependencies.phf]
version = "0.10" version = "0.11"
features = ["macros"] features = ["macros"]
optional = true optional = true
[dependencies.strum_macros] [dependencies.strum_macros]
version = "0.26.3" version = "0.27.1"
optional = true optional = true
[dev-dependencies.strum_macros] [dev-dependencies]
version = "0.26"
[features] [features]
default = ["std"] default = ["std"]

View File

@@ -11,7 +11,7 @@ Strum is a set of macros and traits for working with enums and strings easier in
# Compatibility # Compatibility
Strum is currently compatible with versions of rustc >= 1.56.1. Pull Requests that improve compatibility with older Strum is currently compatible with versions of rustc >= 1.66.1. Pull Requests that improve compatibility with older
versions are welcome. The project goal is to support a rust version for at least 2 years after release versions are welcome. The project goal is to support a rust version for at least 2 years after release
and even longer is preferred since this project changes slowly. and even longer is preferred since this project changes slowly.
@@ -22,11 +22,11 @@ Cargo.toml. Strum_macros contains the macros needed to derive all the traits in
```toml ```toml
[dependencies] [dependencies]
strum = "0.26" strum = "0.27"
strum_macros = "0.26" strum_macros = "0.27"
# You can also use the "derive" feature, and import the macros directly from "strum" # You can also use the "derive" feature, and import the macros directly from "strum"
# strum = { version = "0.26", features = ["derive"] } # strum = { version = "0.27", features = ["derive"] }
``` ```
# Strum Macros # Strum Macros

View File

@@ -74,6 +74,12 @@
//! The plugin will fail if the data doesn't implement From<&str>. You can only have one `default` //! The plugin will fail if the data doesn't implement From<&str>. You can only have one `default`
//! on your enum. //! on your enum.
//! //!
//! - `transparent`: Signals that the inner field's implementation should be used, instead of generating
//! one for this variant. Only applicable to enum variants with a single field. Compatible with the
//! `AsRefStr`, `Display` and `IntoStaticStr` derive macros. Note that `IntoStaticStr` has a few restrictions,
//! the value must be `'static` and `const_into_str` is not supported in combination with `transparent` b/c
//! transparent relies on a call on `From::from(variant)`.
//!
//! - `disabled`: removes variant from generated code. //! - `disabled`: removes variant from generated code.
//! //!
//! - `ascii_case_insensitive`: makes the comparison to this variant case insensitive (ASCII only). //! - `ascii_case_insensitive`: makes the comparison to this variant case insensitive (ASCII only).

View File

@@ -16,11 +16,11 @@
//! //!
//! ```toml //! ```toml
//! [dependencies] //! [dependencies]
//! strum = "0.26" //! strum = "0.27"
//! strum_macros = "0.26" //! strum_macros = "0.27"
//! //!
//! # You can also access strum_macros exports directly through strum using the "derive" feature //! # You can also access strum_macros exports directly through strum using the "derive" feature
//! strum = { version = "0.26", features = ["derive"] } //! strum = { version = "0.27", features = ["derive"] }
//! ``` //! ```
//! //!
@@ -155,9 +155,8 @@ pub trait EnumMessage {
/// `EnumProperty` is a trait that makes it possible to store additional information /// `EnumProperty` is a trait that makes it possible to store additional information
/// with enum variants. This trait is designed to be used with the macro of the same /// with enum variants. This trait is designed to be used with the macro of the same
/// name in the `strum_macros` crate. Currently, the only string literals are supported /// name in the `strum_macros` crate. Currently, the string, integer and bool literals
/// in attributes, the other methods will be implemented as additional attribute types /// are supported in attributes.
/// become stabilized.
/// ///
/// # Example /// # Example
/// ///
@@ -168,27 +167,24 @@ pub trait EnumMessage {
/// ///
/// #[derive(PartialEq, Eq, Debug, EnumProperty)] /// #[derive(PartialEq, Eq, Debug, EnumProperty)]
/// enum Class { /// enum Class {
/// #[strum(props(Teacher="Ms.Frizzle", Room="201"))] /// #[strum(props(Teacher="Ms.Frizzle", Room="201", students=16, mandatory=true))]
/// History, /// History,
/// #[strum(props(Teacher="Mr.Smith"))] /// #[strum(props(Teacher="Mr.Smith"))]
/// #[strum(props(Room="103"))] /// #[strum(props(Room="103", students=10))]
/// Mathematics, /// Mathematics,
/// #[strum(props(Time="2:30"))] /// #[strum(props(Time="2:30", mandatory=true))]
/// Science, /// Science,
/// } /// }
/// ///
/// let history = Class::History; /// let history = Class::History;
/// assert_eq!("Ms.Frizzle", history.get_str("Teacher").unwrap()); /// assert_eq!("Ms.Frizzle", history.get_str("Teacher").unwrap());
/// assert_eq!(16, history.get_int("students").unwrap());
/// assert!(history.get_bool("mandatory").unwrap());
/// ``` /// ```
pub trait EnumProperty { pub trait EnumProperty {
fn get_str(&self, prop: &str) -> Option<&'static str>; fn get_str(&self, prop: &str) -> Option<&'static str>;
fn get_int(&self, _prop: &str) -> Option<usize> { fn get_int(&self, _prop: &str) -> Option<i64>;
Option::None fn get_bool(&self, _prop: &str) -> Option<bool>;
}
fn get_bool(&self, _prop: &str) -> Option<bool> {
Option::None
}
} }
/// A cheap reference-to-reference conversion. Used to convert a value to a /// A cheap reference-to-reference conversion. Used to convert a value to a
@@ -217,6 +213,15 @@ pub trait VariantNames {
const VARIANTS: &'static [&'static str]; const VARIANTS: &'static [&'static str];
} }
/// A trait for retrieving the enum generated by [`EnumDiscriminants`] from an associated
/// Type on the original enumeration. This trait can be autoderived by `strum_macros`.
pub trait IntoDiscriminant {
/// Enum listing the same variants as this enum but without any data fields
type Discriminant;
fn discriminant(&self) -> Self::Discriminant;
}
/// A trait for retrieving a static array containing all the variants in an Enum. /// A trait for retrieving a static array containing all the variants in an Enum.
/// This trait can be autoderived by `strum_macros`. For derived usage, all the /// This trait can be autoderived by `strum_macros`. For derived usage, all the
/// variants in the enumerator need to be unit-types, which means you can't autoderive /// variants in the enumerator need to be unit-types, which means you can't autoderive

View File

@@ -1 +1 @@
{"files":{"Cargo.toml":"8ec1aea0236e97817ede93c32ac56fcd04bf9cc561fa8a553ea329fa0fa639e2","LICENSE":"8bce3b45e49ecd1461f223b46de133d8f62cd39f745cfdaf81bee554b908bd42","README.md":"df67b984209ce474de5d60994983f6d2db0ac3b73bcfc2b1329871b0035c57e6","src/helpers/case_style.rs":"ac429454fad24d1a5a9829711f2024ae9477ffad7cc293b711fe588d1a5e1edf","src/helpers/inner_variant_props.rs":"09c4a2c73aadaaa934e6a20b429b99d4229ce76a4cc1edc916298100d971deb4","src/helpers/metadata.rs":"a9391071f1d4750781eda79bdf4553e77c65c28b1df87dfb3d00df6b290c18dd","src/helpers/mod.rs":"dc171dd27e723aede6c45cb981d48c710f42167afb06a5fbf013470a2962b9f2","src/helpers/type_props.rs":"cb1cdfb0e7927d3b0e364237e7048285ef5968e036d2ebacea642c66d96cc669","src/helpers/variant_props.rs":"36cc466e29b20246f87b9b87d39e4d23545596c522a201e0fb320ac2b231b045","src/lib.rs":"6b3d94635c078f4659500e31c3b682be6a64b5fb4b757e34d9aae3fa37afc10e","src/macros/enum_count.rs":"44084ab800ca8fca3b17f76c6025e8e59855598c0119807ce7bc80d5dc345d99","src/macros/enum_discriminants.rs":"98abbefad100dda4aaafa959ebb9fa77f518dd483414113e6c8bd1eea193bdff","src/macros/enum_is.rs":"cd63fb79f4f9b3479f11bce2ad45d3cb5d23f1d5c9c2a5fbb7af7e813fb70fa7","src/macros/enum_iter.rs":"462f949e7cb4ff3b7a7e30b723a3f86609e0e14c0f8e6b76e095376b0277396d","src/macros/enum_messages.rs":"ee89c3a10ebb553aa9c342f4b3b4346e97be1744fc5df72f580a331d4ea87393","src/macros/enum_properties.rs":"a9e1bf27504d46df689aad8910c7ad8ae7b3780ee97b6e659b2b19e481474030","src/macros/enum_table.rs":"434da77cbca12082d4daeba28ef0e416cea3064f1f641b31f4a330589369e04f","src/macros/enum_try_as.rs":"8bd311522786f0186290ea31a6f3483aa3fa23ccb3441b7fcf9b3743c9d3670b","src/macros/enum_variant_array.rs":"cb8de5cb5841fa9514c423c195b47a2fc13b9f5fb257093311fbb9c136c737d9","src/macros/enum_variant_names.rs":"ad4d2f87bf26e4d07327896118382a4b83c2cca5de6fdfecca6e7639eb73118b","src/macros/from_repr.rs":"561a6f10372c365674e064b31c6eb4c531ffa0b39f03476452bb0746201d579d","src/macros/mod.rs":"c94b29d4ad0f40a7803605d42647cc9fafec76545c7f3c435fe675a3102eb0ef","src/macros/strings/as_ref_str.rs":"594f29efd111ceef258ab0dd449db4cb52e638e1bd17efe589c5a90ee03686b9","src/macros/strings/display.rs":"5e466307196c428da9d31f8e7db46976a077d3e48805d93fa8a178563cc5b599","src/macros/strings/from_string.rs":"53d298f6859df3c13197a8bd303971d2a9ac14cb9860ea1e7c4df1bffdea58bd","src/macros/strings/mod.rs":"b7937f72a46c807fd87c787f3d23029509565a0388a30106e7026363782f2b56","src/macros/strings/to_string.rs":"983e6c1b1dec145acfa0c6a7ef8ff01d30507145753a1d85d0387c5ab61f6fa1"},"package":"4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"} {"files":{"Cargo.toml":"5462d13348e20938685838699bb51ca8c33d2f3156d3d39a43f73894e019e23e","LICENSE":"8bce3b45e49ecd1461f223b46de133d8f62cd39f745cfdaf81bee554b908bd42","README.md":"fbde582a544c0f2a60eb2b274ef60bbab5cf6f527e4dba0170e440898a8e10c5","src/helpers/case_style.rs":"ac429454fad24d1a5a9829711f2024ae9477ffad7cc293b711fe588d1a5e1edf","src/helpers/inner_variant_props.rs":"70f8056195979cc700717f0eed5743c9320246bd3dda675429ad3bacffe26ad5","src/helpers/metadata.rs":"ad83eeedec42e122a36f9207f4a8fee5f25728f8d22886f93487376a3bbcbb01","src/helpers/mod.rs":"205eb143d1ae494333a5ce2f254bf6f1fbe73dec925075fc6cc5e34df9db46b5","src/helpers/type_props.rs":"62ad9f5caa67bc86b3b8ab340f19df787bd6b5d54ab629a088f7e1f3269970d8","src/helpers/variant_props.rs":"3b12e69e354b9966281d71842aa95319826c2b642c9955c6ea75dfe834363468","src/lib.rs":"cb5536c5316066e39f8657f3614a68a7876629e66b992e5646fb0fd702a08766","src/macros/enum_count.rs":"44084ab800ca8fca3b17f76c6025e8e59855598c0119807ce7bc80d5dc345d99","src/macros/enum_discriminants.rs":"91da7a9b42f2b97fecea5a62010dd7b9b77aedbadc862e008a1f0a4712db0336","src/macros/enum_is.rs":"cd63fb79f4f9b3479f11bce2ad45d3cb5d23f1d5c9c2a5fbb7af7e813fb70fa7","src/macros/enum_iter.rs":"c1c7253945d30294e0bd1916847fed1c9d795be02be4ba293f30dd4ba9bd70d4","src/macros/enum_messages.rs":"bf8a6e007a9833b78648cfe99adbafcfd4b72659d1e7d874149ec8f1a987b241","src/macros/enum_properties.rs":"e9f64d4c20a7730ee846ab91aeee24042d18bcda199763133a8ea0d166101a1b","src/macros/enum_table.rs":"86a1b1cc43516578e013c80b4ed4a14fc94e710c1cb7a75229fac465e2cf957c","src/macros/enum_try_as.rs":"ffd5b5ab740d80fd9e08d3db356584fd05e3194ada8d89dfe4f3e825016c1e85","src/macros/enum_variant_array.rs":"cb8de5cb5841fa9514c423c195b47a2fc13b9f5fb257093311fbb9c136c737d9","src/macros/enum_variant_names.rs":"ad4d2f87bf26e4d07327896118382a4b83c2cca5de6fdfecca6e7639eb73118b","src/macros/from_repr.rs":"f06358808bb69eed2c28cccb15865c6fa3c8fb91435fcd2c083a06af3e6f404b","src/macros/mod.rs":"c94b29d4ad0f40a7803605d42647cc9fafec76545c7f3c435fe675a3102eb0ef","src/macros/strings/as_ref_str.rs":"dc84e6627fd0ddea8a5ef60cf999f8da15c26f77d3bbebca01343ecef7e18128","src/macros/strings/display.rs":"b197fbc90acde0ce615f0be4d36065527b8bb50fc6ec8a227d5684c448f82df4","src/macros/strings/from_string.rs":"dced80df02abc3eba9b59402132eafc5b6220d48f7630f5eac4a4444d6d546eb","src/macros/strings/mod.rs":"95d921d854704028ae38961d7ebba13fbb3f6ee35d131de2c3a514594f435058","src/macros/strings/to_string.rs":"983e6c1b1dec145acfa0c6a7ef8ff01d30507145753a1d85d0387c5ab61f6fa1"},"package":"c77a8c5abcaf0f9ce05d62342b7d298c346515365c36b673df4ebe3ced01fde8"}

View File

@@ -10,15 +10,11 @@
# See Cargo.toml.orig for the original contents. # See Cargo.toml.orig for the original contents.
[package] [package]
edition = "2018" edition = "2021"
rust-version = "1.66.1"
name = "strum_macros" name = "strum_macros"
version = "0.26.4" version = "0.27.1"
authors = ["Peter Glotfelty <peter.glotfelty@microsoft.com>"] authors = ["Peter Glotfelty <peter.glotfelty@microsoft.com>"]
build = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Helpful macros for working with enums and strings" description = "Helpful macros for working with enums and strings"
homepage = "https://github.com/Peternator7/strum" homepage = "https://github.com/Peternator7/strum"
documentation = "https://docs.rs/strum" documentation = "https://docs.rs/strum"
@@ -38,7 +34,6 @@ repository = "https://github.com/Peternator7/strum"
[lib] [lib]
name = "strum_macros" name = "strum_macros"
path = "src/lib.rs"
proc-macro = true proc-macro = true
[dependencies.heck] [dependencies.heck]
@@ -55,10 +50,6 @@ version = "1.0"
[dependencies.syn] [dependencies.syn]
version = "2.0" version = "2.0"
features = [ features = ["parsing"]
"parsing",
"extra-traits",
]
[dev-dependencies.strum] [dev-dependencies]
version = "0.26"

View File

@@ -11,7 +11,7 @@ Strum is a set of macros and traits for working with enums and strings easier in
# Compatibility # Compatibility
Strum is currently compatible with versions of rustc >= 1.56.1. Pull Requests that improve compatibility with older Strum is currently compatible with versions of rustc >= 1.66.1. Pull Requests that improve compatibility with older
versions are welcome. The project goal is to support a rust version for at least 2 years after release versions are welcome. The project goal is to support a rust version for at least 2 years after release
and even longer is preferred since this project changes slowly. and even longer is preferred since this project changes slowly.
@@ -22,11 +22,11 @@ Cargo.toml. Strum_macros contains the macros needed to derive all the traits in
```toml ```toml
[dependencies] [dependencies]
strum = "0.26" strum = "0.27"
strum_macros = "0.26" strum_macros = "0.27"
# You can also use the "derive" feature, and import the macros directly from "strum" # You can also use the "derive" feature, and import the macros directly from "strum"
# strum = { version = "0.26", features = ["derive"] } # strum = { version = "0.27", features = ["derive"] }
``` ```
# Strum Macros # Strum Macros

View File

@@ -6,7 +6,7 @@ pub trait HasInnerVariantProperties {
fn get_variant_inner_properties(&self) -> syn::Result<StrumInnerVariantProperties>; fn get_variant_inner_properties(&self) -> syn::Result<StrumInnerVariantProperties>;
} }
#[derive(Clone, Eq, PartialEq, Debug, Default)] #[derive(Clone, Default)]
pub struct StrumInnerVariantProperties { pub struct StrumInnerVariantProperties {
pub default_with: Option<LitStr>, pub default_with: Option<LitStr>,
} }

View File

@@ -16,8 +16,11 @@ pub mod kw {
// enum metadata // enum metadata
custom_keyword!(serialize_all); custom_keyword!(serialize_all);
custom_keyword!(const_into_str);
custom_keyword!(use_phf); custom_keyword!(use_phf);
custom_keyword!(prefix); custom_keyword!(prefix);
custom_keyword!(parse_err_ty);
custom_keyword!(parse_err_fn);
// enum discriminant metadata // enum discriminant metadata
custom_keyword!(derive); custom_keyword!(derive);
@@ -29,6 +32,7 @@ pub mod kw {
custom_keyword!(detailed_message); custom_keyword!(detailed_message);
custom_keyword!(serialize); custom_keyword!(serialize);
custom_keyword!(to_string); custom_keyword!(to_string);
custom_keyword!(transparent);
custom_keyword!(disabled); custom_keyword!(disabled);
custom_keyword!(default); custom_keyword!(default);
custom_keyword!(default_with); custom_keyword!(default_with);
@@ -51,6 +55,15 @@ pub enum EnumMeta {
kw: kw::prefix, kw: kw::prefix,
prefix: LitStr, prefix: LitStr,
}, },
ParseErrTy {
kw: kw::parse_err_ty,
path: Path,
},
ParseErrFn {
kw: kw::parse_err_fn,
path: Path,
},
ConstIntoStr(kw::const_into_str),
} }
impl Parse for EnumMeta { impl Parse for EnumMeta {
@@ -80,6 +93,18 @@ impl Parse for EnumMeta {
input.parse::<Token![=]>()?; input.parse::<Token![=]>()?;
let prefix = input.parse()?; let prefix = input.parse()?;
Ok(EnumMeta::Prefix { kw, prefix }) Ok(EnumMeta::Prefix { kw, prefix })
} else if lookahead.peek(kw::parse_err_ty) {
let kw = input.parse::<kw::parse_err_ty>()?;
input.parse::<Token![=]>()?;
let path: Path = input.parse()?;
Ok(EnumMeta::ParseErrTy { kw, path })
} else if lookahead.peek(kw::parse_err_fn) {
let kw = input.parse::<kw::parse_err_fn>()?;
input.parse::<Token![=]>()?;
let path: Path = input.parse()?;
Ok(EnumMeta::ParseErrFn { kw, path })
} else if lookahead.peek(kw::const_into_str) {
Ok(EnumMeta::ConstIntoStr(input.parse()?))
} else { } else {
Err(lookahead.error()) Err(lookahead.error())
} }
@@ -87,7 +112,7 @@ impl Parse for EnumMeta {
} }
pub enum EnumDiscriminantsMeta { pub enum EnumDiscriminantsMeta {
Derive { kw: kw::derive, paths: Vec<Path> }, Derive { _kw: kw::derive, paths: Vec<Path> },
Name { kw: kw::name, name: Ident }, Name { kw: kw::name, name: Ident },
Vis { kw: kw::vis, vis: Visibility }, Vis { kw: kw::vis, vis: Visibility },
Other { path: Path, nested: TokenStream }, Other { path: Path, nested: TokenStream },
@@ -96,12 +121,12 @@ pub enum EnumDiscriminantsMeta {
impl Parse for EnumDiscriminantsMeta { impl Parse for EnumDiscriminantsMeta {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
if input.peek(kw::derive) { if input.peek(kw::derive) {
let kw = input.parse()?; let _kw = input.parse()?;
let content; let content;
parenthesized!(content in input); parenthesized!(content in input);
let paths = content.parse_terminated(Path::parse, Token![,])?; let paths = content.parse_terminated(Path::parse, Token![,])?;
Ok(EnumDiscriminantsMeta::Derive { Ok(EnumDiscriminantsMeta::Derive {
kw, _kw,
paths: paths.into_iter().collect(), paths: paths.into_iter().collect(),
}) })
} else if input.peek(kw::name) { } else if input.peek(kw::name) {
@@ -154,7 +179,7 @@ pub enum VariantMeta {
value: LitStr, value: LitStr,
}, },
Serialize { Serialize {
kw: kw::serialize, _kw: kw::serialize,
value: LitStr, value: LitStr,
}, },
Documentation { Documentation {
@@ -164,6 +189,7 @@ pub enum VariantMeta {
kw: kw::to_string, kw: kw::to_string,
value: LitStr, value: LitStr,
}, },
Transparent(kw::transparent),
Disabled(kw::disabled), Disabled(kw::disabled),
Default(kw::default), Default(kw::default),
DefaultWith { DefaultWith {
@@ -175,8 +201,8 @@ pub enum VariantMeta {
value: bool, value: bool,
}, },
Props { Props {
kw: kw::props, _kw: kw::props,
props: Vec<(LitStr, LitStr)>, props: Vec<(LitStr, Lit)>,
}, },
} }
@@ -194,15 +220,17 @@ impl Parse for VariantMeta {
let value = input.parse()?; let value = input.parse()?;
Ok(VariantMeta::DetailedMessage { kw, value }) Ok(VariantMeta::DetailedMessage { kw, value })
} else if lookahead.peek(kw::serialize) { } else if lookahead.peek(kw::serialize) {
let kw = input.parse()?; let _kw = input.parse()?;
let _: Token![=] = input.parse()?; let _: Token![=] = input.parse()?;
let value = input.parse()?; let value = input.parse()?;
Ok(VariantMeta::Serialize { kw, value }) Ok(VariantMeta::Serialize { _kw, value })
} else if lookahead.peek(kw::to_string) { } else if lookahead.peek(kw::to_string) {
let kw = input.parse()?; let kw = input.parse()?;
let _: Token![=] = input.parse()?; let _: Token![=] = input.parse()?;
let value = input.parse()?; let value = input.parse()?;
Ok(VariantMeta::ToString { kw, value }) Ok(VariantMeta::ToString { kw, value })
} else if lookahead.peek(kw::transparent) {
Ok(VariantMeta::Transparent(input.parse()?))
} else if lookahead.peek(kw::disabled) { } else if lookahead.peek(kw::disabled) {
Ok(VariantMeta::Disabled(input.parse()?)) Ok(VariantMeta::Disabled(input.parse()?))
} else if lookahead.peek(kw::default) { } else if lookahead.peek(kw::default) {
@@ -222,12 +250,12 @@ impl Parse for VariantMeta {
}; };
Ok(VariantMeta::AsciiCaseInsensitive { kw, value }) Ok(VariantMeta::AsciiCaseInsensitive { kw, value })
} else if lookahead.peek(kw::props) { } else if lookahead.peek(kw::props) {
let kw = input.parse()?; let _kw = input.parse()?;
let content; let content;
parenthesized!(content in input); parenthesized!(content in input);
let props = content.parse_terminated(Prop::parse, Token![,])?; let props = content.parse_terminated(Prop::parse, Token![,])?;
Ok(VariantMeta::Props { Ok(VariantMeta::Props {
kw, _kw,
props: props props: props
.into_iter() .into_iter()
.map(|Prop(k, v)| (LitStr::new(&k.to_string(), k.span()), v)) .map(|Prop(k, v)| (LitStr::new(&k.to_string(), k.span()), v))
@@ -239,7 +267,7 @@ impl Parse for VariantMeta {
} }
} }
struct Prop(Ident, LitStr); struct Prop(Ident, Lit);
impl Parse for Prop { impl Parse for Prop {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
@@ -295,7 +323,6 @@ fn get_metadata_inner<'a, T: Parse>(
}) })
} }
#[derive(Debug)]
pub enum InnerVariantMeta { pub enum InnerVariantMeta {
DefaultWith { kw: kw::default_with, value: LitStr }, DefaultWith { kw: kw::default_with, value: LitStr },
} }

View File

@@ -13,6 +13,13 @@ use proc_macro2::Span;
use quote::ToTokens; use quote::ToTokens;
use syn::spanned::Spanned; use syn::spanned::Spanned;
pub fn missing_parse_err_attr_error() -> syn::Error {
syn::Error::new(
Span::call_site(),
"`parse_err_ty` and `parse_err_fn` attributes are both required.",
)
}
pub fn non_enum_error() -> syn::Error { pub fn non_enum_error() -> syn::Error {
syn::Error::new(Span::call_site(), "This macro only supports enums.") syn::Error::new(Span::call_site(), "This macro only supports enums.")
} }
@@ -25,6 +32,16 @@ pub fn non_unit_variant_error() -> syn::Error {
) )
} }
pub fn non_single_field_variant_error(attr: &str) -> syn::Error {
syn::Error::new(
Span::call_site(),
format_args!(
"The [`{}`] attribute only supports enum variants with a single field",
attr
),
)
}
pub fn strum_discriminants_passthrough_error(span: &impl Spanned) -> syn::Error { pub fn strum_discriminants_passthrough_error(span: &impl Spanned) -> syn::Error {
syn::Error::new( syn::Error::new(
span.span(), span.span(),

View File

@@ -11,8 +11,10 @@ pub trait HasTypeProperties {
fn get_type_properties(&self) -> syn::Result<StrumTypeProperties>; fn get_type_properties(&self) -> syn::Result<StrumTypeProperties>;
} }
#[derive(Debug, Clone, Default)] #[derive(Clone, Default)]
pub struct StrumTypeProperties { pub struct StrumTypeProperties {
pub parse_err_ty: Option<Path>,
pub parse_err_fn: Option<Path>,
pub case_style: Option<CaseStyle>, pub case_style: Option<CaseStyle>,
pub ascii_case_insensitive: bool, pub ascii_case_insensitive: bool,
pub crate_module_path: Option<Path>, pub crate_module_path: Option<Path>,
@@ -23,6 +25,7 @@ pub struct StrumTypeProperties {
pub use_phf: bool, pub use_phf: bool,
pub prefix: Option<LitStr>, pub prefix: Option<LitStr>,
pub enum_repr: Option<TokenStream>, pub enum_repr: Option<TokenStream>,
pub const_into_str: bool,
} }
impl HasTypeProperties for DeriveInput { impl HasTypeProperties for DeriveInput {
@@ -32,11 +35,15 @@ impl HasTypeProperties for DeriveInput {
let strum_meta = self.get_metadata()?; let strum_meta = self.get_metadata()?;
let discriminants_meta = self.get_discriminants_metadata()?; let discriminants_meta = self.get_discriminants_metadata()?;
let mut parse_err_ty_kw = None;
let mut parse_err_fn_kw = None;
let mut serialize_all_kw = None; let mut serialize_all_kw = None;
let mut ascii_case_insensitive_kw = None; let mut ascii_case_insensitive_kw = None;
let mut use_phf_kw = None; let mut use_phf_kw = None;
let mut crate_module_path_kw = None; let mut crate_module_path_kw = None;
let mut prefix_kw = None; let mut prefix_kw = None;
let mut const_into_str = None;
for meta in strum_meta { for meta in strum_meta {
match meta { match meta {
EnumMeta::SerializeAll { case_style, kw } => { EnumMeta::SerializeAll { case_style, kw } => {
@@ -82,6 +89,30 @@ impl HasTypeProperties for DeriveInput {
prefix_kw = Some(kw); prefix_kw = Some(kw);
output.prefix = Some(prefix); output.prefix = Some(prefix);
} }
EnumMeta::ParseErrTy { path, kw } => {
if let Some(fst_kw) = parse_err_ty_kw {
return Err(occurrence_error(fst_kw, kw, "parse_err_ty"));
}
parse_err_ty_kw = Some(kw);
output.parse_err_ty = Some(path);
}
EnumMeta::ParseErrFn { path, kw } => {
if let Some(fst_kw) = parse_err_fn_kw {
return Err(occurrence_error(fst_kw, kw, "parse_err_fn"));
}
parse_err_fn_kw = Some(kw);
output.parse_err_fn = Some(path);
}
EnumMeta::ConstIntoStr(kw) => {
if let Some(fst_kw) = const_into_str {
return Err(occurrence_error(fst_kw, kw, "const_into_str"));
}
const_into_str = Some(kw);
output.const_into_str = true;
}
} }
} }

View File

@@ -1,5 +1,5 @@
use std::default::Default; use std::default::Default;
use syn::{Ident, LitStr, Variant}; use syn::{Ident, Lit, LitStr, Variant};
use super::case_style::{CaseStyle, CaseStyleHelpers}; use super::case_style::{CaseStyle, CaseStyleHelpers};
use super::metadata::{kw, VariantExt, VariantMeta}; use super::metadata::{kw, VariantExt, VariantMeta};
@@ -9,8 +9,9 @@ pub trait HasStrumVariantProperties {
fn get_variant_properties(&self) -> syn::Result<StrumVariantProperties>; fn get_variant_properties(&self) -> syn::Result<StrumVariantProperties>;
} }
#[derive(Clone, Eq, PartialEq, Debug, Default)] #[derive(Clone, Default)]
pub struct StrumVariantProperties { pub struct StrumVariantProperties {
pub transparent: Option<kw::transparent>,
pub disabled: Option<kw::disabled>, pub disabled: Option<kw::disabled>,
pub default: Option<kw::default>, pub default: Option<kw::default>,
pub default_with: Option<LitStr>, pub default_with: Option<LitStr>,
@@ -18,7 +19,7 @@ pub struct StrumVariantProperties {
pub message: Option<LitStr>, pub message: Option<LitStr>,
pub detailed_message: Option<LitStr>, pub detailed_message: Option<LitStr>,
pub documentation: Vec<LitStr>, pub documentation: Vec<LitStr>,
pub string_props: Vec<(LitStr, LitStr)>, pub props: Vec<(LitStr, Lit)>,
serialize: Vec<LitStr>, serialize: Vec<LitStr>,
pub to_string: Option<LitStr>, pub to_string: Option<LitStr>,
ident: Option<Ident>, ident: Option<Ident>,
@@ -73,6 +74,7 @@ impl HasStrumVariantProperties for Variant {
let mut message_kw = None; let mut message_kw = None;
let mut detailed_message_kw = None; let mut detailed_message_kw = None;
let mut transparent_kw = None;
let mut disabled_kw = None; let mut disabled_kw = None;
let mut default_kw = None; let mut default_kw = None;
let mut default_with_kw = None; let mut default_with_kw = None;
@@ -110,6 +112,14 @@ impl HasStrumVariantProperties for Variant {
to_string_kw = Some(kw); to_string_kw = Some(kw);
output.to_string = Some(value); output.to_string = Some(value);
} }
VariantMeta::Transparent(kw) => {
if let Some(fst_kw) = transparent_kw {
return Err(occurrence_error(fst_kw, kw, "transparent"));
}
transparent_kw = Some(kw);
output.transparent = Some(kw);
}
VariantMeta::Disabled(kw) => { VariantMeta::Disabled(kw) => {
if let Some(fst_kw) = disabled_kw { if let Some(fst_kw) = disabled_kw {
return Err(occurrence_error(fst_kw, kw, "disabled")); return Err(occurrence_error(fst_kw, kw, "disabled"));
@@ -143,7 +153,7 @@ impl HasStrumVariantProperties for Variant {
output.ascii_case_insensitive = Some(value); output.ascii_case_insensitive = Some(value);
} }
VariantMeta::Props { props, .. } => { VariantMeta::Props { props, .. } => {
output.string_props.extend(props); output.props.extend(props);
} }
} }
} }

View File

@@ -54,7 +54,13 @@ fn debug_print_generated(ast: &DeriveInput, toks: &TokenStream) {
/// If you have a large enum, you may want to consider using the `use_phf` attribute here. It leverages /// If you have a large enum, you may want to consider using the `use_phf` attribute here. It leverages
/// perfect hash functions to parse much quicker than a standard `match`. (MSRV 1.46) /// perfect hash functions to parse much quicker than a standard `match`. (MSRV 1.46)
/// ///
/// # Example howto use `EnumString` /// The default error type is `strum::ParseError`. This can be overriden by applying both the
/// `parse_err_ty` and `parse_err_fn` attributes at the type level. `parse_error_fn` should be a
/// function that accepts an `&str` and returns the type `parse_error_ty`. See
/// [this test case](https://github.com/Peternator7/strum/blob/9db3c4dc9b6f585aeb9f5f15f9cc18b6cf4fd780/strum_tests/tests/from_str.rs#L233)
/// for an example.
///
/// # Example how to use `EnumString`
/// ``` /// ```
/// use std::str::FromStr; /// use std::str::FromStr;
/// use strum_macros::EnumString; /// use strum_macros::EnumString;
@@ -154,10 +160,13 @@ pub fn from_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
/// let yellow = Color::Yellow; /// let yellow = Color::Yellow;
/// assert_eq!("Yellow", yellow.as_ref()); /// assert_eq!("Yellow", yellow.as_ref());
/// // or for string formatting /// // or for string formatting
/// println!( /// assert_eq!(
/// "blue: {} green: {}", /// "blue: Blue green: Green",
/// Color::Blue(10).as_ref(), /// format!(
/// Color::Green { range: 42 }.as_ref() /// "blue: {} green: {}",
/// Color::Blue(10).as_ref(),
/// Color::Green { range: 42 }.as_ref()
/// )
/// ); /// );
/// ///
/// // With prefix on all variants /// // With prefix on all variants
@@ -237,7 +246,8 @@ pub fn variant_names_deprecated(input: proc_macro::TokenStream) -> proc_macro::T
/// meaning that the variants must not have any data. /// meaning that the variants must not have any data.
/// ///
/// ``` /// ```
/// use strum::VariantArray; /// use strum::VariantArray as _;
/// use strum_macros::VariantArray;
/// ///
/// #[derive(VariantArray, Debug, PartialEq, Eq)] /// #[derive(VariantArray, Debug, PartialEq, Eq)]
/// enum Op { /// enum Op {
@@ -411,10 +421,13 @@ pub fn to_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
/// let yellow = Color::Yellow; /// let yellow = Color::Yellow;
/// assert_eq!(String::from("Yellow"), yellow.to_string()); /// assert_eq!(String::from("Yellow"), yellow.to_string());
/// // or for string formatting /// // or for string formatting
/// println!( /// assert_eq!(
/// "blue: {} green: {}", /// "blue: Blue green: Green",
/// Color::Blue(10), /// format!(
/// Color::Green { range: 42 } /// "blue: {} green: {}",
/// Color::Blue(10),
/// Color::Green { range: 42 }
/// )
/// ); /// );
/// // you can also use named fields in message /// // you can also use named fields in message
/// let purple = Color::Purple { sat: 10 }; /// let purple = Color::Purple { sat: 10 };
@@ -429,7 +442,7 @@ pub fn display(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
toks.into() toks.into()
} }
/// Creates a new type that iterates of the variants of an enum. /// Creates a new type that iterates over the variants of an enum.
/// ///
/// Iterate over the variants of an Enum. Any additional data on your variants will be set to `Default::default()`. /// Iterate over the variants of an Enum. Any additional data on your variants will be set to `Default::default()`.
/// The macro implements [`strum::IntoEnumIterator`](https://docs.rs/strum/latest/strum/trait.IntoEnumIterator.html) on your enum and creates a new type called `YourEnumIter` that is the iterator object. /// The macro implements [`strum::IntoEnumIterator`](https://docs.rs/strum/latest/strum/trait.IntoEnumIterator.html) on your enum and creates a new type called `YourEnumIter` that is the iterator object.
@@ -830,8 +843,8 @@ pub fn enum_properties(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
/// ``` /// ```
/// // Bring trait into scope /// // Bring trait into scope
/// use std::str::FromStr; /// use std::str::FromStr;
/// use strum::{IntoEnumIterator, EnumMessage}; /// use strum::{IntoEnumIterator, EnumMessage as _};
/// use strum_macros::{EnumDiscriminants, EnumIter, EnumString}; /// use strum_macros::{EnumDiscriminants, EnumIter, EnumString, EnumMessage};
/// ///
/// #[derive(Debug)] /// #[derive(Debug)]
/// struct NonDefault; /// struct NonDefault;

View File

@@ -22,6 +22,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
// Derives for the generated enum // Derives for the generated enum
let type_properties = ast.get_type_properties()?; let type_properties = ast.get_type_properties()?;
let strum_module_path = type_properties.crate_module_path();
let derives = type_properties.discriminant_derives; let derives = type_properties.discriminant_derives;
@@ -35,7 +36,8 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name); let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name);
let discriminants_vis = type_properties let discriminants_vis = type_properties
.discriminant_vis .discriminant_vis
.unwrap_or_else(|| vis.clone()); .as_ref()
.unwrap_or_else(|| &vis);
// Pass through all other attributes // Pass through all other attributes
let pass_though_attributes = type_properties.discriminant_others; let pass_though_attributes = type_properties.discriminant_others;
@@ -132,6 +134,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let impl_from = quote! { let impl_from = quote! {
impl #impl_generics ::core::convert::From< #name #ty_generics > for #discriminants_name #where_clause { impl #impl_generics ::core::convert::From< #name #ty_generics > for #discriminants_name #where_clause {
#[inline]
fn from(val: #name #ty_generics) -> #discriminants_name { fn from(val: #name #ty_generics) -> #discriminants_name {
#from_fn_body #from_fn_body
} }
@@ -149,6 +152,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
quote! { quote! {
impl #impl_generics ::core::convert::From< #enum_life #name #ty_generics > for #discriminants_name #where_clause { impl #impl_generics ::core::convert::From< #enum_life #name #ty_generics > for #discriminants_name #where_clause {
#[inline]
fn from(val: #enum_life #name #ty_generics) -> #discriminants_name { fn from(val: #enum_life #name #ty_generics) -> #discriminants_name {
#from_fn_body #from_fn_body
} }
@@ -156,6 +160,26 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
}; };
// For now, only implement IntoDiscriminant if the user has not overriden the visibility.
let impl_into_discriminant = match type_properties.discriminant_vis {
// If the visibilty is unspecified or `pub` then we implement IntoDiscriminant
None | Some(syn::Visibility::Public(..)) => quote! {
impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause {
type Discriminant = #discriminants_name;
#[inline]
fn discriminant(&self) -> Self::Discriminant {
<Self::Discriminant as ::core::convert::From<&Self>>::from(self)
}
}
},
// If it's something restricted such as `pub(super)` then we skip implementing the
// trait for now. There are certainly scenarios where they could be equivalent, but
// as a heuristic, if someone is overriding the visibility, it's because they want
// the discriminant type to be less visible than the original type.
_ => quote! {},
};
Ok(quote! { Ok(quote! {
/// Auto-generated discriminant enum variants /// Auto-generated discriminant enum variants
#derives #derives
@@ -165,6 +189,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
#(#discriminants),* #(#discriminants),*
} }
#impl_into_discriminant
#impl_from #impl_from
#impl_from_ref #impl_from_ref
}) })

View File

@@ -23,9 +23,9 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let phantom_data = if gen.type_params().count() > 0 { let phantom_data = if gen.type_params().count() > 0 {
let g = gen.type_params().map(|param| &param.ident); let g = gen.type_params().map(|param| &param.ident);
quote! { < ( #(#g),* ) > } quote! { < fn() -> ( #(#g),* ) > }
} else { } else {
quote! { < () > } quote! { < fn() -> () > }
}; };
let variants = match &ast.data { let variants = match &ast.data {
@@ -100,6 +100,8 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause { impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause {
type Iterator = #iter_name #ty_generics; type Iterator = #iter_name #ty_generics;
#[inline]
fn iter() -> #iter_name #ty_generics { fn iter() -> #iter_name #ty_generics {
#iter_name { #iter_name {
idx: 0, idx: 0,
@@ -112,15 +114,18 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl #impl_generics Iterator for #iter_name #ty_generics #where_clause { impl #impl_generics Iterator for #iter_name #ty_generics #where_clause {
type Item = #name #ty_generics; type Item = #name #ty_generics;
#[inline]
fn next(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> { fn next(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> {
self.nth(0) self.nth(0)
} }
#[inline]
fn size_hint(&self) -> (usize, ::core::option::Option<usize>) { fn size_hint(&self) -> (usize, ::core::option::Option<usize>) {
let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx }; let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx };
(t, Some(t)) (t, Some(t))
} }
#[inline]
fn nth(&mut self, n: usize) -> ::core::option::Option<<Self as Iterator>::Item> { fn nth(&mut self, n: usize) -> ::core::option::Option<<Self as Iterator>::Item> {
let idx = self.idx + n + 1; let idx = self.idx + n + 1;
if idx + self.back_idx > #variant_count { if idx + self.back_idx > #variant_count {
@@ -137,12 +142,14 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause { impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause {
#[inline]
fn len(&self) -> usize { fn len(&self) -> usize {
self.size_hint().0 self.size_hint().0
} }
} }
impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause { impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause {
#[inline]
fn next_back(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> { fn next_back(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> {
let back_idx = self.back_idx + 1; let back_idx = self.back_idx + 1;
@@ -162,6 +169,7 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl #impl_generics ::core::iter::FusedIterator for #iter_name #ty_generics #where_clause { } impl #impl_generics ::core::iter::FusedIterator for #iter_name #ty_generics #where_clause { }
impl #impl_generics Clone for #iter_name #ty_generics #where_clause { impl #impl_generics Clone for #iter_name #ty_generics #where_clause {
#[inline]
fn clone(&self) -> #iter_name #ty_generics { fn clone(&self) -> #iter_name #ty_generics {
#iter_name { #iter_name {
idx: self.idx, idx: self.idx,

View File

@@ -113,24 +113,28 @@ pub fn enum_message_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
Ok(quote! { Ok(quote! {
impl #impl_generics #strum_module_path::EnumMessage for #name #ty_generics #where_clause { impl #impl_generics #strum_module_path::EnumMessage for #name #ty_generics #where_clause {
#[inline]
fn get_message(&self) -> ::core::option::Option<&'static str> { fn get_message(&self) -> ::core::option::Option<&'static str> {
match self { match self {
#(#arms),* #(#arms),*
} }
} }
#[inline]
fn get_detailed_message(&self) -> ::core::option::Option<&'static str> { fn get_detailed_message(&self) -> ::core::option::Option<&'static str> {
match self { match self {
#(#detailed_arms),* #(#detailed_arms),*
} }
} }
#[inline]
fn get_documentation(&self) -> ::core::option::Option<&'static str> { fn get_documentation(&self) -> ::core::option::Option<&'static str> {
match self { match self {
#(#documentation_arms),* #(#documentation_arms),*
} }
} }
#[inline]
fn get_serializations(&self) -> &'static [&'static str] { fn get_serializations(&self) -> &'static [&'static str] {
match self { match self {
#(#serializations),* #(#serializations),*

View File

@@ -1,9 +1,24 @@
use std::collections::HashMap;
use proc_macro2::TokenStream; use proc_macro2::TokenStream;
use quote::quote; use quote::quote;
use syn::{Data, DeriveInput, Fields}; use syn::{Data, DeriveInput, Fields, Lit};
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};
#[derive(Hash, PartialEq, Eq)]
enum PropertyType {
String,
Integer,
Bool,
}
const PROPERTY_TYPES: [PropertyType; 3] = [
PropertyType::String,
PropertyType::Integer,
PropertyType::Bool,
];
pub fn enum_properties_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { pub fn enum_properties_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident; let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
@@ -14,11 +29,12 @@ pub fn enum_properties_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let type_properties = ast.get_type_properties()?; let type_properties = ast.get_type_properties()?;
let strum_module_path = type_properties.crate_module_path(); let strum_module_path = type_properties.crate_module_path();
let mut arms = Vec::new(); let mut built_arms: HashMap<_, _> = PROPERTY_TYPES.iter().map(|p| (p, Vec::new())).collect();
for variant in variants { for variant in variants {
let ident = &variant.ident; let ident = &variant.ident;
let variant_properties = variant.get_variant_properties()?; let variant_properties = variant.get_variant_properties()?;
let mut string_arms = Vec::new(); let mut arms: HashMap<_, _> = PROPERTY_TYPES.iter().map(|p| (p, Vec::new())).collect();
// But you can disable the messages. // But you can disable the messages.
if variant_properties.disabled.is_some() { if variant_properties.disabled.is_some() {
continue; continue;
@@ -30,32 +46,69 @@ pub fn enum_properties_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
Fields::Named(..) => quote! { {..} }, Fields::Named(..) => quote! { {..} },
}; };
for (key, value) in variant_properties.string_props { for (key, value) in variant_properties.props {
string_arms.push(quote! { #key => ::core::option::Option::Some( #value )}); let property_type = match value {
Lit::Str(..) => PropertyType::String,
Lit::Bool(..) => PropertyType::Bool,
Lit::Int(..) => PropertyType::Integer,
_ => todo!("TODO"),
};
arms.get_mut(&property_type)
.unwrap()
.push(quote! { #key => ::core::option::Option::Some( #value )});
} }
string_arms.push(quote! { _ => ::core::option::Option::None }); for property in &PROPERTY_TYPES {
arms.get_mut(&property)
arms.push(quote! { .unwrap()
&#name::#ident #params => { .push(quote! { _ => ::core::option::Option::None });
match prop { let arms_as_string = &arms[property];
#(#string_arms),* built_arms.get_mut(&property).unwrap().push(quote! {
&#name::#ident #params => {
match prop {
#(#arms_as_string),*
}
} }
} });
}); }
} }
if arms.len() < variants.len() { for (_, arms) in built_arms.iter_mut() {
arms.push(quote! { _ => ::core::option::Option::None }); if arms.len() < variants.len() {
arms.push(quote! { _ => ::core::option::Option::None });
}
} }
let (built_string_arms, built_int_arms, built_bool_arms) = (
&built_arms[&PropertyType::String],
&built_arms[&PropertyType::Integer],
&built_arms[&PropertyType::Bool],
);
Ok(quote! { Ok(quote! {
impl #impl_generics #strum_module_path::EnumProperty for #name #ty_generics #where_clause { impl #impl_generics #strum_module_path::EnumProperty for #name #ty_generics #where_clause {
#[inline]
fn get_str(&self, prop: &str) -> ::core::option::Option<&'static str> { fn get_str(&self, prop: &str) -> ::core::option::Option<&'static str> {
match self { match self {
#(#arms),* #(#built_string_arms),*
} }
} }
#[inline]
fn get_int(&self, prop: &str) -> ::core::option::Option<i64> {
match self {
#(#built_int_arms),*
}
}
#[inline]
fn get_bool(&self, prop: &str) -> ::core::option::Option<bool> {
match self {
#(#built_bool_arms),*
}
}
} }
}) })
} }

View File

@@ -58,7 +58,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
// Error on variants with data // Error on variants with data
if variant.fields != Fields::Unit { if !matches!(variant.fields, Fields::Unit) {
return Err(syn::Error::new( return Err(syn::Error::new(
variant.fields.span(), variant.fields.span(),
"`EnumTable` doesn't support enums with non-unit variants", "`EnumTable` doesn't support enums with non-unit variants",
@@ -133,6 +133,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl<T> #table_name<T> { impl<T> #table_name<T> {
#[doc = #doc_new] #[doc = #doc_new]
#[inline]
#vis fn new( #vis fn new(
#(#snake_idents: T,)* #(#snake_idents: T,)*
) -> #table_name<T> { ) -> #table_name<T> {
@@ -142,6 +143,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
#[doc = #doc_closure] #[doc = #doc_closure]
#[inline]
#vis fn from_closure<F: Fn(#name)->T>(func: F) -> #table_name<T> { #vis fn from_closure<F: Fn(#name)->T>(func: F) -> #table_name<T> {
#table_name { #table_name {
#(#closure_fields)* #(#closure_fields)*
@@ -149,6 +151,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
#[doc = #doc_transform] #[doc = #doc_transform]
#[inline]
#vis fn transform<U, F: Fn(#name, &T)->U>(&self, func: F) -> #table_name<U> { #vis fn transform<U, F: Fn(#name, &T)->U>(&self, func: F) -> #table_name<U> {
#table_name { #table_name {
#(#transform_fields)* #(#transform_fields)*
@@ -160,6 +163,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl<T> ::core::ops::Index<#name> for #table_name<T> { impl<T> ::core::ops::Index<#name> for #table_name<T> {
type Output = T; type Output = T;
#[inline]
fn index(&self, idx: #name) -> &T { fn index(&self, idx: #name) -> &T {
match idx { match idx {
#(#get_matches)* #(#get_matches)*
@@ -169,6 +173,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
impl<T> ::core::ops::IndexMut<#name> for #table_name<T> { impl<T> ::core::ops::IndexMut<#name> for #table_name<T> {
#[inline]
fn index_mut(&mut self, idx: #name) -> &mut T { fn index_mut(&mut self, idx: #name) -> &mut T {
match idx { match idx {
#(#get_matches_mut)* #(#get_matches_mut)*
@@ -179,6 +184,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl<T> #table_name<::core::option::Option<T>> { impl<T> #table_name<::core::option::Option<T>> {
#[doc = #doc_option_all] #[doc = #doc_option_all]
#[inline]
#vis fn all(self) -> ::core::option::Option<#table_name<T>> { #vis fn all(self) -> ::core::option::Option<#table_name<T>> {
if let #table_name { if let #table_name {
#(#snake_idents: ::core::option::Option::Some(#snake_idents),)* #(#snake_idents: ::core::option::Option::Some(#snake_idents),)*
@@ -194,6 +200,7 @@ pub fn enum_table_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl<T, E> #table_name<::core::result::Result<T, E>> { impl<T, E> #table_name<::core::result::Result<T, E>> {
#[doc = #doc_result_all_ok] #[doc = #doc_result_all_ok]
#[inline]
#vis fn all_ok(self) -> ::core::result::Result<#table_name<T>, E> { #vis fn all_ok(self) -> ::core::result::Result<#table_name<T>, E> {
::core::result::Result::Ok(#table_name { ::core::result::Result::Ok(#table_name {
#(#snake_idents: self.#snake_idents?,)* #(#snake_idents: self.#snake_idents?,)*

View File

@@ -23,7 +23,7 @@ pub fn enum_try_as_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
syn::Fields::Unnamed(values) => { syn::Fields::Unnamed(values) => {
let variant_name = &variant.ident; let variant_name = &variant.ident;
let types: Vec<_> = values.unnamed.iter().map(|field| { let types: Vec<_> = values.unnamed.iter().map(|field| {
field.to_token_stream() field.ty.to_token_stream()
}).collect(); }).collect();
let field_names: Vec<_> = values.unnamed.iter().enumerate().map(|(i, _)| { let field_names: Vec<_> = values.unnamed.iter().enumerate().map(|(i, _)| {
let name = "x".repeat(i + 1); let name = "x".repeat(i + 1);

View File

@@ -113,6 +113,7 @@ pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
#[allow(clippy::use_self)] #[allow(clippy::use_self)]
impl #impl_generics #name #ty_generics #where_clause { impl #impl_generics #name #ty_generics #where_clause {
#[doc = "Try to create [Self] from the raw representation"] #[doc = "Try to create [Self] from the raw representation"]
#[inline]
#vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> {
#(#constant_defs)* #(#constant_defs)*
match discriminant { match discriminant {

View File

@@ -2,9 +2,14 @@ use proc_macro2::TokenStream;
use quote::quote; use quote::quote;
use syn::{parse_quote, Data, DeriveInput, Fields}; use syn::{parse_quote, Data, DeriveInput, Fields};
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; use crate::helpers::{
non_enum_error, non_single_field_variant_error, HasStrumVariantProperties, HasTypeProperties,
};
fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> { fn get_arms<F>(ast: &DeriveInput, transparent_fn: F) -> syn::Result<Vec<TokenStream>>
where
F: Fn(&TokenStream) -> TokenStream,
{
let name = &ast.ident; let name = &ast.ident;
let mut arms = Vec::new(); let mut arms = Vec::new();
let variants = match &ast.data { let variants = match &ast.data {
@@ -22,12 +27,21 @@ fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> {
continue; continue;
} }
if let Some(..) = variant_properties.transparent {
let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
transparent_fn(tok)
})
.map_err(|_| non_single_field_variant_error("transparent"))?;
arms.push(arm);
continue;
}
// Look at all the serialize attributes. // Look at all the serialize attributes.
// Use `to_string` attribute (not `as_ref_str` or something) to keep things consistent // Use `to_string` attribute (not `as_ref_str` or something) to keep things consistent
// (i.e. always `enum.as_ref().to_string() == enum.to_string()`). // (i.e. always `enum.as_ref().to_string() == enum.to_string()`).
let output = variant_properties let output = variant_properties
.get_preferred_name(type_properties.case_style, type_properties.prefix.as_ref()); .get_preferred_name(type_properties.case_style, type_properties.prefix.as_ref());
let params = match variant.fields { let params = match variant.fields {
Fields::Unit => quote! {}, Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) }, Fields::Unnamed(..) => quote! { (..) },
@@ -52,9 +66,13 @@ fn get_arms(ast: &DeriveInput) -> syn::Result<Vec<TokenStream>> {
pub fn as_ref_str_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { pub fn as_ref_str_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident; let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let arms = get_arms(ast)?; let arms = get_arms(ast, |tok| {
quote! { ::core::convert::AsRef::<str>::as_ref(#tok) }
})?;
Ok(quote! { Ok(quote! {
impl #impl_generics ::core::convert::AsRef<str> for #name #ty_generics #where_clause { impl #impl_generics ::core::convert::AsRef<str> for #name #ty_generics #where_clause {
#[inline]
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
match *self { match *self {
#(#arms),* #(#arms),*
@@ -75,7 +93,10 @@ pub fn as_static_str_inner(
) -> syn::Result<TokenStream> { ) -> syn::Result<TokenStream> {
let name = &ast.ident; let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let arms = get_arms(ast)?; let arms = &get_arms(ast, |tok| {
quote! { ::core::convert::From::from(#tok) }
})?;
let type_properties = ast.get_type_properties()?; let type_properties = ast.get_type_properties()?;
let strum_module_path = type_properties.crate_module_path(); let strum_module_path = type_properties.crate_module_path();
@@ -86,12 +107,11 @@ pub fn as_static_str_inner(
parse_quote!('_derivative_strum), parse_quote!('_derivative_strum),
))); )));
let (impl_generics2, _, _) = generics.split_for_impl(); let (impl_generics2, _, _) = generics.split_for_impl();
let arms2 = arms.clone();
let arms3 = arms.clone();
Ok(match trait_variant { Ok(match trait_variant {
GenerateTraitVariant::AsStaticStr => quote! { GenerateTraitVariant::AsStaticStr => quote! {
impl #impl_generics #strum_module_path::AsStaticRef<str> for #name #ty_generics #where_clause { impl #impl_generics #strum_module_path::AsStaticRef<str> for #name #ty_generics #where_clause {
#[inline]
fn as_static(&self) -> &'static str { fn as_static(&self) -> &'static str {
match *self { match *self {
#(#arms),* #(#arms),*
@@ -99,19 +119,43 @@ pub fn as_static_str_inner(
} }
} }
}, },
GenerateTraitVariant::From if !type_properties.const_into_str => quote! {
impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause {
#[inline]
fn from(x: #name #ty_generics) -> &'static str {
match x {
#(#arms),*
}
}
}
impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause {
#[inline]
fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str {
match *x {
#(#arms),*
}
}
}
},
GenerateTraitVariant::From => quote! { GenerateTraitVariant::From => quote! {
impl #impl_generics #name #ty_generics #where_clause {
pub const fn into_str(&self) -> &'static str {
match self {
#(#arms),*
}
}
}
impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause { impl #impl_generics ::core::convert::From<#name #ty_generics> for &'static str #where_clause {
fn from(x: #name #ty_generics) -> &'static str { fn from(x: #name #ty_generics) -> &'static str {
match x { match x {
#(#arms2),* #(#arms),*
} }
} }
} }
impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause { impl #impl_generics2 ::core::convert::From<&'_derivative_strum #name #ty_generics> for &'static str #where_clause {
fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str { fn from(x: &'_derivative_strum #name #ty_generics) -> &'static str {
match *x { x.into_str()
#(#arms3),*
}
} }
} }
}, },

View File

@@ -2,7 +2,9 @@ use proc_macro2::{Ident, TokenStream};
use quote::quote; use quote::quote;
use syn::{punctuated::Punctuated, Data, DeriveInput, Fields, LitStr, Token}; use syn::{punctuated::Punctuated, Data, DeriveInput, Fields, LitStr, Token};
use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties}; use crate::helpers::{
non_enum_error, non_single_field_variant_error, HasStrumVariantProperties, HasTypeProperties,
};
pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident; let name = &ast.ident;
@@ -23,6 +25,16 @@ pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
continue; continue;
} }
if let Some(..) = variant_properties.transparent {
let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
quote! { ::core::fmt::Display::fmt(#tok, f) }
})
.map_err(|_| non_single_field_variant_error("transparent"))?;
arms.push(arm);
continue;
}
// Look at all the serialize attributes. // Look at all the serialize attributes.
let output = variant_properties let output = variant_properties
.get_preferred_name(type_properties.case_style, type_properties.prefix.as_ref()); .get_preferred_name(type_properties.case_style, type_properties.prefix.as_ref());
@@ -37,7 +49,8 @@ pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
.enumerate() .enumerate()
.map(|(index, field)| { .map(|(index, field)| {
assert!(field.ident.is_none()); assert!(field.ident.is_none());
let ident = syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap(); let ident =
syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap();
quote! { ref #ident } quote! { ref #ident }
}) })
.collect(); .collect();
@@ -59,86 +72,87 @@ pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
}; };
if variant_properties.to_string.is_none() && variant_properties.default.is_some() { if variant_properties.to_string.is_none() && variant_properties.default.is_some() {
match &variant.fields { let arm = super::extract_single_field_variant_and_then(name, variant, |tok| {
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => { quote! { ::core::fmt::Display::fmt(#tok, f)}
arms.push(quote! { #name::#ident(ref s) => ::core::fmt::Display::fmt(s, f) }); })
} .map_err(|_| {
_ => { syn::Error::new_spanned(
return Err(syn::Error::new_spanned( variant,
variant, "Default only works on newtype structs with a single String field",
"Default only works on newtype structs with a single String field", )
)) })?;
}
}
} else {
let arm = match variant.fields {
Fields::Named(ref field_names) => {
let used_vars = capture_format_string_idents(&output)?;
if used_vars.is_empty() {
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
} else {
// Create args like 'name = name, age = age' for format macro
let args: Punctuated<_, Token!(,)> = field_names
.named
.iter()
.filter_map(|field| {
let ident = field.ident.as_ref().unwrap();
// Only contain variables that are used in format string
if !used_vars.contains(ident) {
None
} else {
Some(quote! { #ident = #ident })
}
})
.collect();
quote! {
#[allow(unused_variables)]
#name::#ident #params => ::core::fmt::Display::fmt(&format!(#output, #args), f)
}
}
},
Fields::Unnamed(ref unnamed_fields) => {
let used_vars = capture_format_strings(&output)?;
if used_vars.iter().any(String::is_empty) {
return Err(syn::Error::new_spanned(
&output,
"Empty {} is not allowed; Use manual numbering ({0})",
))
}
if used_vars.is_empty() {
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
} else {
let args: Punctuated<_, Token!(,)> = unnamed_fields
.unnamed
.iter()
.enumerate()
.map(|(index, field)| {
assert!(field.ident.is_none());
syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap()
})
.collect();
quote! {
#[allow(unused_variables)]
#name::#ident #params => ::core::fmt::Display::fmt(&format!(#output, #args), f)
}
}
}
Fields::Unit => {
let used_vars = capture_format_strings(&output)?;
if !used_vars.is_empty() {
return Err(syn::Error::new_spanned(
&output,
"Unit variants do not support interpolation",
));
}
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
}
};
arms.push(arm); arms.push(arm);
continue;
} }
let arm = match variant.fields {
Fields::Named(ref field_names) => {
let used_vars = capture_format_string_idents(&output)?;
if used_vars.is_empty() {
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
} else {
// Create args like 'name = name, age = age' for format macro
let args: Punctuated<_, Token!(,)> = field_names
.named
.iter()
.filter_map(|field| {
let ident = field.ident.as_ref().unwrap();
// Only contain variables that are used in format string
if !used_vars.contains(ident) {
None
} else {
Some(quote! { #ident = #ident })
}
})
.collect();
quote! {
#[allow(unused_variables)]
#name::#ident #params => ::core::fmt::Display::fmt(&format_args!(#output, #args), f)
}
}
}
Fields::Unnamed(ref unnamed_fields) => {
let used_vars = capture_format_strings(&output)?;
if used_vars.iter().any(String::is_empty) {
return Err(syn::Error::new_spanned(
&output,
"Empty {} is not allowed; Use manual numbering ({0})",
));
}
if used_vars.is_empty() {
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
} else {
let args: Punctuated<_, Token!(,)> = unnamed_fields
.unnamed
.iter()
.enumerate()
.map(|(index, field)| {
assert!(field.ident.is_none());
syn::parse_str::<Ident>(format!("field{}", index).as_str()).unwrap()
})
.collect();
quote! {
#[allow(unused_variables)]
#name::#ident #params => ::core::fmt::Display::fmt(&format!(#output, #args), f)
}
}
}
Fields::Unit => {
let used_vars = capture_format_strings(&output)?;
if !used_vars.is_empty() {
return Err(syn::Error::new_spanned(
&output,
"Unit variants do not support interpolation",
));
}
quote! { #name::#ident #params => ::core::fmt::Display::fmt(#output, f) }
}
};
arms.push(arm);
} }
if arms.len() < variants.len() { if arms.len() < variants.len() {
@@ -157,14 +171,17 @@ pub fn display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
} }
fn capture_format_string_idents(string_literal: &LitStr) -> syn::Result<Vec<Ident>> { fn capture_format_string_idents(string_literal: &LitStr) -> syn::Result<Vec<Ident>> {
capture_format_strings(string_literal)?.into_iter().map(|ident| { capture_format_strings(string_literal)?
syn::parse_str::<Ident>(ident.as_str()).map_err(|_| { .into_iter()
syn::Error::new_spanned( .map(|ident| {
string_literal, syn::parse_str::<Ident>(ident.as_str()).map_err(|_| {
"Invalid identifier inside format string bracket", syn::Error::new_spanned(
) string_literal,
"Invalid identifier inside format string bracket",
)
})
}) })
}).collect() .collect()
} }
fn capture_format_strings(string_literal: &LitStr) -> syn::Result<Vec<String>> { fn capture_format_strings(string_literal: &LitStr) -> syn::Result<Vec<String>> {

View File

@@ -1,10 +1,10 @@
use proc_macro2::TokenStream; use proc_macro2::TokenStream;
use quote::quote; use quote::quote;
use syn::{Data, DeriveInput, Fields}; use syn::{parse_quote, Data, DeriveInput, Fields, Path};
use crate::helpers::{ use crate::helpers::{
non_enum_error, occurrence_error, HasInnerVariantProperties, HasStrumVariantProperties, missing_parse_err_attr_error, non_enum_error, occurrence_error, HasInnerVariantProperties,
HasTypeProperties, HasStrumVariantProperties, HasTypeProperties,
}; };
pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
@@ -19,9 +19,25 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let strum_module_path = type_properties.crate_module_path(); let strum_module_path = type_properties.crate_module_path();
let mut default_kw = None; let mut default_kw = None;
let mut default = let (mut default_err_ty, mut default) = match (
quote! { ::core::result::Result::Err(#strum_module_path::ParseError::VariantNotFound) }; type_properties.parse_err_ty,
type_properties.parse_err_fn,
) {
(None, None) => (
quote! { #strum_module_path::ParseError },
quote! { ::core::result::Result::Err(#strum_module_path::ParseError::VariantNotFound) },
),
(Some(ty), Some(f)) => {
let ty_path: Path = parse_quote!(#ty);
let fn_path: Path = parse_quote!(#f);
(
quote! { #ty_path },
quote! { ::core::result::Result::Err(#fn_path(s)) },
)
}
_ => return Err(missing_parse_err_attr_error()),
};
let mut phf_exact_match_arms = Vec::new(); let mut phf_exact_match_arms = Vec::new();
let mut standard_match_arms = Vec::new(); let mut standard_match_arms = Vec::new();
for variant in variants { for variant in variants {
@@ -37,8 +53,21 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
return Err(occurrence_error(fst_kw, kw, "default")); return Err(occurrence_error(fst_kw, kw, "default"));
} }
default_kw = Some(kw);
default_err_ty = quote! { #strum_module_path::ParseError };
match &variant.fields { match &variant.fields {
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {} Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
default = quote! {
::core::result::Result::Ok(#name::#ident(s.into()))
};
}
Fields::Named(ref f) if f.named.len() == 1 => {
let field_name = f.named.last().unwrap().ident.as_ref().unwrap();
default = quote! {
::core::result::Result::Ok(#name::#ident { #field_name : s.into() } )
};
}
_ => { _ => {
return Err(syn::Error::new_spanned( return Err(syn::Error::new_spanned(
variant, variant,
@@ -46,10 +75,7 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
)) ))
} }
} }
default_kw = Some(kw);
default = quote! {
::core::result::Result::Ok(#name::#ident(s.into()))
};
continue; continue;
} }
@@ -146,7 +172,9 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let from_str = quote! { let from_str = quote! {
#[allow(clippy::use_self)] #[allow(clippy::use_self)]
impl #impl_generics ::core::str::FromStr for #name #ty_generics #where_clause { impl #impl_generics ::core::str::FromStr for #name #ty_generics #where_clause {
type Err = #strum_module_path::ParseError; type Err = #default_err_ty;
#[inline]
fn from_str(s: &str) -> ::core::result::Result< #name #ty_generics , <Self as ::core::str::FromStr>::Err> { fn from_str(s: &str) -> ::core::result::Result< #name #ty_generics , <Self as ::core::str::FromStr>::Err> {
#phf_body #phf_body
#standard_match_body #standard_match_body
@@ -158,7 +186,7 @@ pub fn from_string_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
&impl_generics, &impl_generics,
&ty_generics, &ty_generics,
where_clause, where_clause,
&strum_module_path, &default_err_ty,
); );
Ok(quote! { Ok(quote! {
@@ -184,12 +212,14 @@ fn try_from_str(
impl_generics: &syn::ImplGenerics, impl_generics: &syn::ImplGenerics,
ty_generics: &syn::TypeGenerics, ty_generics: &syn::TypeGenerics,
where_clause: Option<&syn::WhereClause>, where_clause: Option<&syn::WhereClause>,
strum_module_path: &syn::Path, default_err_ty: &TokenStream,
) -> TokenStream { ) -> TokenStream {
quote! { quote! {
#[allow(clippy::use_self)] #[allow(clippy::use_self)]
impl #impl_generics ::core::convert::TryFrom<&str> for #name #ty_generics #where_clause { impl #impl_generics ::core::convert::TryFrom<&str> for #name #ty_generics #where_clause {
type Error = #strum_module_path::ParseError; type Error = #default_err_ty;
#[inline]
fn try_from(s: &str) -> ::core::result::Result< #name #ty_generics , <Self as ::core::convert::TryFrom<&str>>::Error> { fn try_from(s: &str) -> ::core::result::Result< #name #ty_generics , <Self as ::core::convert::TryFrom<&str>>::Error> {
::core::str::FromStr::from_str(s) ::core::str::FromStr::from_str(s)
} }

View File

@@ -1,4 +1,49 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Fields, Ident, Variant};
pub mod as_ref_str; pub mod as_ref_str;
pub mod display; pub mod display;
pub mod from_string; pub mod from_string;
pub mod to_string; pub mod to_string;
struct NonSingleFieldEnum;
fn extract_single_field_variant_and_then<F>(
name: &Ident,
variant: &Variant,
return_val_fn: F,
) -> Result<TokenStream, NonSingleFieldEnum>
where
F: Fn(&TokenStream) -> TokenStream,
{
let variant_ident = &variant.ident;
let pattern_and_return = match &variant.fields {
Fields::Unnamed(f) if f.unnamed.len() == 1 => {
let ident = &quote! { field0 };
let ref_kw = match f.unnamed.last().unwrap().ty {
syn::Type::Reference(..) => quote! { },
_ => quote! { ref },
};
let ret_val = return_val_fn(ident);
quote! { (#ref_kw #ident) => #ret_val }
}
Fields::Named(f) if f.named.len() == 1 => {
let field = f.named.last().unwrap();
let ref_kw = match field.ty {
syn::Type::Reference(..) => quote! { },
_ => quote! { ref },
};
let ident = field.ident.as_ref().unwrap();
let ident = &quote! { #ident };
let ret_val = return_val_fn(ident);
quote! { { #ref_kw #ident} => #ret_val }
}
_ => return Err(NonSingleFieldEnum),
};
Ok(quote! { #name::#variant_ident #pattern_and_return })
}