deluxe-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100123240ustar { "git": { "sha1": "550c8ea2831f7104bf3c457db1ea9513c2fa1c31" }, "path_in_vcs": "" }deluxe-0.5.0/COPYING000064400000000000000000000020661046102023000121530ustar 00000000000000MIT License Copyright (c) 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. deluxe-0.5.0/Cargo.toml0000644000000027270000000000100103320ustar # 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 = "deluxe" version = "0.5.0" include = [ "/src", "/tests", "/README.md", "/COPYING", ] description = "Procedural macro attribute parser" homepage = "https://github.com/jf2048/deluxe" documentation = "https://docs.rs/deluxe" readme = "README.md" keywords = [ "macros", "derive", "attributes", ] license = "MIT" repository = "https://github.com/jf2048/deluxe.git" resolver = "2" [dependencies.deluxe-core] version = "0.5.0" default-features = false [dependencies.deluxe-macros] version = "0.5.0" [dependencies.once_cell] version = "1.13.0" [dependencies.proc-macro2] version = "1.0.38" [dependencies.syn] version = "2.0.10" default-features = false [dev-dependencies.deluxe-core] version = "0.5.0" features = ["full"] default-features = false [dev-dependencies.quote] version = "1.0.25" [features] default = [ "full", "proc-macro", ] full = [ "deluxe-core/full", "syn/full", ] proc-macro = [ "deluxe-core/proc-macro", "syn/proc-macro", ] deluxe-0.5.0/Cargo.toml.orig000064400000000000000000000017201046102023000140030ustar 00000000000000[package] name = "deluxe" version = "0.5.0" edition = "2021" description = "Procedural macro attribute parser" license = "MIT" documentation = "https://docs.rs/deluxe" homepage = "https://github.com/jf2048/deluxe" repository = "https://github.com/jf2048/deluxe.git" readme = "README.md" keywords = ["macros", "derive", "attributes"] include = ["/src", "/tests", "/README.md", "/COPYING"] resolver = "2" [features] default = ["full", "proc-macro"] full = ["deluxe-core/full", "syn/full"] proc-macro = ["deluxe-core/proc-macro", "syn/proc-macro"] [dependencies] once_cell = "1.13.0" proc-macro2 = "1.0.38" syn = { version = "2.0.10", default-features = false } deluxe-core = { path = "./core", version = "0.5.0", default-features = false } deluxe-macros = { path = "./macros", version = "0.5.0" } [dev-dependencies] quote = "1.0.25" deluxe-core = { path = "./core", version = "0.5.0", features = ["full"], default-features = false } [workspace] members = ["core", "macros"] deluxe-0.5.0/README.md000064400000000000000000000406151046102023000124010ustar 00000000000000# Deluxe   [![Latest Version]][crates.io] [![Documentation]][docs] [![Build Status]][actions] [Documentation]: https://docs.rs/deluxe/badge.svg [docs]: https://docs.rs/deluxe [Build Status]: https://github.com/jf2048/deluxe/workflows/ci/badge.svg?branch=main [actions]: https://github.com/jf2048/deluxe/actions?query=branch%3Amain [Latest Version]: https://img.shields.io/crates/v/deluxe.svg [crates.io]: https://crates.io/crates/deluxe A Rust procedural macro attribute parser. ### Abstract This crate offers attribute parsing closer to the design of attributes in C#. It has an interface similar to [serde](https://serde.rs). Attributes are written as plain Rust structs or enums, and then parsers for them are generated automatically. They can contain arbitrary expressions and can inherit from other attributes using a flattening mechanism. The parsers in this crate directly parse token streams using [`syn`](https://docs.rs/syn). As a result, most built-in Rust types and `syn` types can be used directly as fields. ### Details Functionality in this crate is centered around three traits, and their respective derive macros: - **[`ExtractAttributes`]** Extracts attributes from an object containing a list of `syn::Attribute`, and parses them into a Rust type. Should be implemented for top-level structures that will be parsed directly out of a set of matching attributes. - **[`ParseAttributes`]** Parses a Rust type from any object containing a list of `syn::Attribute`. Should be used if the set of matching attributes can potentially be shared between this type and other types. - **[`ParseMetaItem`]** Parses a Rust type from a `syn::parse::ParseStream`. Should be implemented for any types that can be nested inside an attribute. Basic usage of this crate in derive macros requires simply deriving one (or a few) of these traits, and then calling [`extract_attributes`] or [`parse_attributes`]. For more advanced functionality, several `#[deluxe(...)]` attributes are supported on structs, enums, variants and fields. See the examples below, and the documentation for each derive macro for a complete description of the supported attributes. A list of field types supported by default can be seen in the list of provided [`ParseMetaItem` implementations](https://docs.rs/deluxe-core/latest/deluxe_core/trait.ParseMetaItem.html#foreign-impls). For more complex usage, manual implementations of these traits can be provided. See the documentation on the individual traits for more details on how to manually implement your own parsers. ### Related Crates Deluxe takes inspiration from the [darling](https://docs.rs/darling) crate, but offers a few enhancements over it. Darling is built around pre-parsed `syn::Meta` objects, and therefore is restricted to the [meta syntax](https://doc.rust-lang.org/stable/reference/attributes.html#meta-item-attribute-syntax). Deluxe parses its types directly from `TokenStream` objects in the attributes and so is able to use any syntax that parses as a valid token tree. Deluxe also does not provide extra traits for parsing special `syn` objects like `DeriveInput` and `Field`. Instead, Deluxe uses a generic trait to parse from any type containing a `Vec`. ### Examples #### Basic Derive Macro To create a derive macro that can add some simple metadata to a Rust type from an attribute, start by defining a struct that derives [`ExtractAttributes`]. Then, call [`extract_attributes`] in your derive macro to create an instance of the struct: ```rust #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_desc))] // Match only `my_desc` attributes struct MyDescription { name: String, version: String, } #[proc_macro_derive(MyDescription, attributes(my_desc))] pub fn derive_my_description(item: TokenStream) -> TokenStream { let mut input = syn::parse::(item).unwrap(); // Extract a description, modifying `input.attrs` to remove the matched attributes. let MyDescription { name, version } = match deluxe::extract_attributes(&mut input) { Ok(desc) => desc, Err(e) => return e.into_compile_error().into() }; let ident = &input.ident; let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl(); let tokens = quote::quote! { impl #impl_generics #ident #type_generics #where_clause { fn my_desc() -> &'static str { concat!("Name: ", #name, ", Version: ", #version) } } }; tokens.into() } ``` Then, try adding the attribute in some code that uses your macro: ```rust #[derive(MyDescription)] #[my_desc(name = "hello world", version = "0.2")] struct Hello(String); let hello = Hello("Moon".into()); assert_eq!(hello.my_desc(), "Name: hello world, Version: 0.2"); ``` #### Basic Attribute Macro The [`parse`] and [`parse2`] functions included in this crate can also be used as simple helpers for attribute macros: ```rust #[derive(deluxe::ParseMetaItem)] struct MyDescription { name: String, version: String, } #[proc_macro_attribute] pub fn my_desc( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let MyDescription { name, version } = match deluxe::parse::(attr) { Ok(desc) => desc, Err(e) => return e.into_compile_error().into() }; let tokens = quote::quote! { fn my_desc() -> &'static str { concat!("Name: ", #name, ", Version: ", #version) } #item }; tokens.into() } ``` ```rust // In your normal code #[my_desc(name = "hello world", version = "0.2")] fn nothing() {} assert_eq!(my_desc(), "Name: hello world, Version: 0.2"); ``` #### Field Attributes The attributes `alias`, `default`, `rename`, and `skip` are supported, and behave the same as in Serde. The `append` attribute can be used on `Vec` fields to aggregate all duplicates of a key. The `rest` attribute can be used to do custom processing on any unknown keys. ```rust #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_object))] struct MyObject { // Can be specified with key `id` or `object_id` #[deluxe(alias = object_id)] id: u64, // Field is optional, defaults to `Default::default` if not present #[deluxe(default)] count: u64, // Defaults to "Empty" if not present #[deluxe(default = String::from("Empty"))] contents: String, // Can be specified only with key `name` #[deluxe(rename = name)] s: String, // Skipped during parsing entirely #[deluxe(skip)] internal_flag: bool, // Appends any extra fields with the key `expr` to the Vec #[deluxe(append, rename = expr)] exprs: Vec, // Adds any unknown keys to the hash map #[deluxe(rest)] rest: std::collections::HashMap, } ``` ```rust // Omitted fields will be set to defaults #[derive(MyObject)] #[my_object(id = 1, name = "First", expr = 1 + 2, count = 3)] struct FirstObject; // `expr` can be specified multiple times because of the `append` attribute #[derive(MyObject)] #[my_object(object_id = 2, name = "Second", expr = 1 + 2, expr = 3 + 4)] struct SecondObject; // `unknown` and `extra` will be stored in the `rest` hashmap #[derive(MyObject)] #[my_object(id = 3, name = "Third", unknown = 1 + 2, extra = 3 + 4)] struct ThirdObject; ``` #### Inheritance The `flatten` attribute can be used to parse keys from one structure inside another: ```rust #[derive(deluxe::ParseMetaItem)] struct A { id: u64, } #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(b))] struct B { #[deluxe(flatten)] a: A, name: String, } ``` Then, fields from both `A` and `B` can be used when deriving `B`: ```rust #[derive(B)] #[b(id = 123, name = "object")] struct Object; ``` #### Attributes in Nested Code Extra attributes can be taken from within the code block attached to a macro. When used in an attribute macro, the attributes should be consumed so as not to produce an "unknown attribute" error when outputting tokens. ```rust #[derive(Default, deluxe::ParseMetaItem, deluxe::ExtractAttributes)] struct MyDescription { name: String, version: String, } #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(author))] struct Authors(#[deluxe(flatten)] Vec); #[proc_macro_derive(MyDescription, attributes(my_desc))] pub fn derive_my_description(item: TokenStream) -> TokenStream { let mut input = syn::parse::(item).unwrap(); // Parsing functions suffixed with `_optional` can be used to continue // parsing after an error. Any errors will get accumulated into an `Errors` // structure, which can then be manually included in the token output to // produce compile errors. let errors = deluxe::Errors::new(); let MyDescription { name, version } = deluxe::extract_attributes_optional(&mut input, &errors); let mut authors = Vec::new(); if let syn::Data::Struct(s) = &mut input.data { // Look through all fields in the struct for `author` attributes for field in s.fields.iter_mut() { // Aggregate any errors to avoid exiting the loop early match deluxe::extract_attributes(field) { Ok(Authors(a)) => authors.extend(a), Err(e) => errors.push_syn(e), } } } let ident = &input.ident; let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl(); // Make sure to include the errors in the output let tokens = quote::quote! { #errors impl #impl_generics #ident #type_generics #where_clause { fn my_desc() -> &'static str { concat!("Name: ", #name, ", Version: ", #version #(, ", Author: ", #authors)*) } } }; tokens.into() } #[proc_macro_attribute] pub fn my_desc_mod( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> proc_macro::TokenStream { let mut module = syn::parse::(item) { Ok(module) => module, Err(e) => return e.into_compile_error().into() }; let errors = deluxe::Errors::new(); let MyDescription { name, version } = deluxe::parse_optional(attr, &errors); let (_, items) = module.content.as_mut().unwrap(); let mut authors = Vec::new(); // Look through all items in the module for `author` attributes for i in items.iter_mut() { // Extract the attributes to remove them from the final output match deluxe::extract_attributes(i) { Ok(Authors(a)) => authors.extend(a), Err(e) => errors.push_syn(e), } } // Place a new function inside the module items.push(syn::parse_quote! { fn my_desc() -> &'static str { concat!("Name: ", #name, ", Version: ", #version #(, ", Author: ", #authors)*) } }); // Make sure to include the errors in the output let tokens = quote::quote! { #module #errors }; tokens.into() } ``` ```rust // In your normal code #[derive(MyDescription, Default)] #[my_desc(name = "hello world", version = "0.2")] struct Hello { #[author("Alice")] a: i32, #[author("Bob")] b: String } let hello: Hello = Default::default(); assert_eq!(hello.my_desc(), "Name: hello world, Version: 0.2, Author: Alice, Author: Bob"); #[my_desc_mod(name = "hello world", version = "0.2")] mod abc { #[author("Alice", "Bob")] fn func1() {} #[author("Carol")] #[author("Dave")] fn func2() {} } assert_eq!( abc::my_desc(), "Name: hello world, Version: 0.2, Author: Alice, Author: Bob, Author: Carol, Author: Dave" ); ``` #### Tuple Structs, Tuples and Vecs Deluxe also supports parsing into data structures with unnamed fields. ```rust #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_tuple))] struct MyTuple(u64, String); #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_idents))] struct MyIdents { id: u64, names: (String, String), idents: Vec } ``` The standard attribute syntax with parenthesis can be used when specifying a `Vec` type. The alternative syntax `key = [...]` can also be used to have an appearance similar to an array literal. ```rust #[derive(MyTuple)] #[my_tuple(123, "object")] struct Object; #[derive(MyIdents)] #[my_idents(id = 7, names("hello", "world"), idents(a, b, c))] struct ABC; // `idents` contains same values as above #[derive(MyIdents)] #[my_idents(id = 7, names("hello", "world"), idents = [a, b, c])] struct ABC2; ``` #### C#-styled Attributes Attributes in C# can support positional arguments first with the named arguments afterwards. This style can be emulated by using a tuple struct with a normal struct flattened at the end. Placing `#[deluxe(default)]` on the struct behaves the same as Serde, by filling in all fields with values from `Default`, allowing every named argument to be optional. ```rust #[derive(deluxe::ParseMetaItem, Default)] #[deluxe(default)] struct Flags { native: bool, } #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(a))] struct A(u64, String, #[deluxe(flatten)] Flags); ``` ```rust #[derive(A)] #[a(123, "object")] struct Object; #[derive(A)] #[a(123, "native-object", native = true)] struct NativeObject; ``` #### Enums Enums are supported by using the variant name as a single key, in snake-case. Variants can be renamed, aliased and skipped in the same way as fields. ```rust #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_enum))] enum MyEnum { A, B, C, #[deluxe(alias = d)] AnotherOne, #[deluxe(rename = e)] AnotherTwo, #[deluxe(skip)] SkipMe } ``` ```rust #[derive(MyEnum)] #[my_enum(b)] struct ObjectB; #[derive(MyEnum)] #[my_enum(another_one)] struct ObjectD; ``` #### Complex Enums Enums with struct and tuple variants are also supported. The data inside is used as arguments to the attribute. All field attributes from structs are also supported inside variants. Additionally, enum variants with named fields can be flattened. The behavior of a flattened variant is similar to Serde's `untagged` mode. In a flattened variant, the name of the variant will be ignored. Instead, Deluxe will attempt to use the unique keys in each variant to determine if that variant was specified. A compile error will be thrown if it is not possible to determine a unique, unambiguous key between two variants. ```rust #[derive(deluxe::ExtractAttributes)] #[deluxe(attributes(my_enum))] enum MyEnum { A, B(u64, String), C { id: u64, name: String }, #[deluxe(flatten)] D { d: u64, name: String }, } ``` ```rust #[derive(MyEnum)] #[my_enum(a)] struct ObjectA; #[derive(MyEnum)] #[my_enum(b(1, "hello"))] struct ObjectB; #[derive(MyEnum)] #[my_enum(c(id = 2, name = "world"))] struct ObjectC; // No inner parenthesis needed here due to flattening #[derive(MyEnum)] #[my_enum(d = 3, name = "moon")] struct ObjectD; ``` #### Storing Containers During parsing, Deluxe can store references to the container type holding the attributes for easier access. Container fields are skipped during attribute parsing. ```rust #[derive(deluxe::ParseAttributes)] #[deluxe(attributes(my_object))] struct MyObject<'t> { id: u64, // Fill `container` in using the parsed type. Note this restricts the // derived `ParseAttributes` impl so it can only be used on `DeriveInput`. #[deluxe(container)] container: &'t syn::DeriveInput, } #[proc_macro_derive(MyObject, attributes(my_desc))] pub fn derive_my_object(item: TokenStream) -> TokenStream { let input = syn::parse::(item).unwrap(); // `obj.container` now holds a reference to `input` let obj: MyObject = match deluxe::parse_attributes(&input) { Ok(obj) => obj, Err(e) => return e.into_compile_error().into() }; let tokens = quote::quote! { /* ... generate some code here ... */ }; tokens.into() } ``` To support both extracting and parsing, a container field can also be a value type. In that case, the container will be cloned into the structure. [`ParseMetaItem`]: (https://docs.rs/deluxe/latest/deluxe/derive.ParseMetaItem.html) [`ParseAttributes`]: (https://docs.rs/deluxe/latest/deluxe/derive.ParseAttributes.html) [`ExtractAttributes`]: (https://docs.rs/deluxe/latest/deluxe/derive.ExtractAttributes.html) [`parse_attributes`]: (https://docs.rs/deluxe/latest/deluxe/fn.parse_attributes.html) [`extract_attributes`]: (https://docs.rs/deluxe/latest/deluxe/fn.extract_attributes.html) [`parse`]: (https://docs.rs/deluxe/latest/deluxe/fn.parse.html) [`parse2`]: (https://docs.rs/deluxe/latest/deluxe/fn.parse2.html) deluxe-0.5.0/src/lib.rs000064400000000000000000000625271046102023000130330ustar 00000000000000//! # Deluxe //! //! A procedural macro attribute parser. //! //! ### Abstract //! //! This crate offers attribute parsing closer to the design of attributes in C#. It has an //! interface similar to [serde](https://serde.rs). Attributes are written as plain Rust structs or //! enums, and then parsers for them are generated automatically. They can contain arbitrary //! expressions and can inherit from other attributes using a flattening mechanism. //! //! The parsers in this crate directly parse token streams using [`syn`]. As a result, most //! built-in Rust types and `syn` types can be used directly as fields. //! //! ### Usage //! //! Functionality in this crate is centered around three traits, and their respective derive macros: //! - **[`ExtractAttributes`](macro@ExtractAttributes)** //! //! Extracts attributes from an object containing a list of [`syn::Attribute`], and parses them //! into a Rust type. Should be implemented for top-level structures that will be parsed directly //! out of a set of matching attributes. //! - **[`ParseAttributes`](macro@ParseAttributes)** //! //! Parses a Rust type from any object containing a list of [`syn::Attribute`]. Should be used if //! the set of matching attributes can potentially be shared between this type and other types. //! - **[`ParseMetaItem`](macro@ParseMetaItem)** //! //! Parses a Rust type from a [`ParseStream`](syn::parse::ParseStream). Should be implemented for //! any types that can be nested inside an attribute. //! //! Basic usage of this crate in derive macros requires simply deriving one (or a few) of these //! traits, and then calling [`extract_attributes`] or [`parse_attributes`]. For more advanced //! functionality, several `#[deluxe(...)]` attributes are supported on structs, enums, variants //! and fields. See the examples below, and the documentation for each derive macro for a complete //! description of the supported attributes. //! //! A list of field types supported by default can be seen in the list of provided [`ParseMetaItem` //! implementations](trait@ParseMetaItem#foreign-impls). For more complex usage, manual //! implementations of these traits can be provided. See the documentation on individual traits in //! [`deluxe_core`] for more details on how to manually implement your own parsers. //! //! ### Related Crates //! //! Deluxe takes inspiration from the [darling](https://docs.rs/darling) crate, but offers a few //! enhancements over it. Darling is built around pre-parsed [`syn::Meta`] objects, and therefore //! is restricted to the [meta //! syntax](https://doc.rust-lang.org/stable/reference/attributes.html#meta-item-attribute-syntax). //! Deluxe parses its types directly from [`TokenStream`](proc_macro2::TokenStream) objects in the //! attributes and so is able to use any syntax that parses as a valid token tree. Deluxe also does //! not provide extra traits for parsing special `syn` objects like //! [`DeriveInput`](syn::DeriveInput) and [`Field`](syn::Field). Instead, Deluxe uses a generic //! trait to parse from any type containing a [Vec]<[syn::Attribute]>. //! //! ### Examples //! //! #### Basic Derive Macro //! //! To create a derive macro that can add some simple metadata to a Rust type from an attribute, //! start by defining a struct that derives [`ExtractAttributes`](macro@ExtractAttributes). Then, //! call [`extract_attributes`] in your derive macro to create an instance of the struct: //! //! ``` //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_desc))] //! struct MyDescription { //! name: String, //! version: String, //! } //! //! fn my_derive(item: proc_macro2::TokenStream) -> deluxe::Result { //! let mut input = syn::parse2::(item)?; //! //! // Extract the attributes! //! let MyDescription { name, version } = deluxe::extract_attributes(&mut input)?; //! //! // Now get some info to generate an associated function... //! let ident = &input.ident; //! let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl(); //! //! Ok(quote::quote! { //! impl #impl_generics #ident #type_generics #where_clause { //! fn my_desc() -> &'static str { //! concat!("Name: ", #name, ", Version: ", #version) //! } //! } //! }) //! } //! //! # let tokens = my_derive(quote::quote! { //! # #[my_desc(name = "hello world", version = "0.2")] //! # struct Hello; //! # }).unwrap(); //! # let i: syn::ItemImpl = syn::parse_quote! { #tokens }; //! # assert_eq!(i, syn::parse_quote! { //! # impl Hello { //! # fn my_desc() -> &'static str { //! # concat!("Name: ", "hello world", ", Version: ", "0.2") //! # } //! # } //! # }); //! ``` //! //! Then, try adding the attribute in some code that uses your macro: //! //! ```ignore //! // In your macros crate //! //! #[proc_macro_derive(MyDescription, attributes(my_desc))] //! pub fn derive_my_description(item: proc_macro::TokenStream) -> proc_macro::TokenStream { //! my_derive(item.into()).unwrap().into() //! } //! ``` //! //! ```ignore //! // In your normal code //! //! #[derive(MyDescription, Default)] //! #[my_desc(name = "hello world", version = "0.2")] //! struct Hello { //! a: i32, //! b: String //! } //! //! let hello: Hello = Default::default(); //! assert_eq!(hello.my_desc(), "Name: hello world, Version: 0.2"); //! ``` //! //! #### Basic Attribute Macro //! //! The `parse` and `parse2` functions included in this crate can also be used as simple helpers //! for attribute macros: //! //! ``` //! #[derive(deluxe::ParseMetaItem)] //! struct MyDescription { //! name: String, //! version: String, //! } //! //! fn my_desc_attr( //! attr: proc_macro2::TokenStream, //! item: proc_macro2::TokenStream, //! ) -> deluxe::Result { //! let MyDescription { name, version } = deluxe::parse2::(attr)?; //! //! Ok(quote::quote! { //! fn my_desc() -> &'static str { //! concat!("Name: ", #name, ", Version: ", #version) //! } //! #item //! }) //! } //! //! # let tokens = my_desc_attr( //! # quote::quote!(name = "hello world", version = "0.2"), //! # quote::quote!(), //! # ).unwrap(); //! # let f: syn::ItemFn = syn::parse_quote! { #tokens }; //! # assert_eq!(f, syn::parse_quote! { //! # fn my_desc() -> &'static str { //! # concat!("Name: ", "hello world", ", Version: ", "0.2") //! # } //! # }); //! ``` //! //! ```ignore //! // In your macros crate //! //! #[proc_macro_attribute] //! pub fn my_desc( //! attr: proc_macro::TokenStream, //! item: proc_macro::TokenStream, //! ) -> proc_macro::TokenStream { //! my_desc_attr(attr.into(), item.into()).unwrap().into() //! } //! ``` //! //! ```ignore //! // In your normal code //! //! #[my_desc(name = "hello world", version = "0.2")] //! fn nothing() {} //! //! assert_eq!(my_desc(), "Name: hello world, Version: 0.2"); //! ``` //! //! #### Field Attributes //! //! The attributes [`alias`](macro@ParseMetaItem#deluxealias--ident-1), //! [`default`](macro@ParseMetaItem#deluxedefault-1), //! [`rename`](macro@ParseMetaItem#deluxerename--ident-1), and //! [`skip`](macro@ParseMetaItem#deluxeskip-1) are supported, and behave the same as in Serde. The //! [`append`](macro@ParseMetaItem#deluxeappend) attribute can be used on [`Vec`] fields to //! aggregate all duplicates of a key. The [`rest`](macro@ParseMetaItem#deluxerest) attribute can //! be used to do custom processing on any unknown keys. //! //! ``` //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_object))] //! struct MyObject { //! // Can be specified with key `id` or `object_id` //! #[deluxe(alias = object_id)] //! id: u64, //! //! // Field is optional, defaults to `Default::default` if not present //! #[deluxe(default)] //! count: u64, //! //! // Defaults to "Empty" if not present //! #[deluxe(default = String::from("Empty"))] //! contents: String, //! //! // Can be specified only with key `name` //! #[deluxe(rename = name)] //! s: String, //! //! // Skipped during parsing entirely //! #[deluxe(skip)] //! internal_flag: bool, //! //! // Appends any extra fields with the key `expr` to the Vec //! #[deluxe(append, rename = expr)] //! exprs: Vec, //! //! // Adds any unknown keys to the hash map //! #[deluxe(rest)] //! rest: std::collections::HashMap, //! } //! ``` //! //! ```ignore //! // Omitted fields will be set to defaults //! #[derive(MyObject)] //! #[my_object(id = 1, name = "First", expr = 1 + 2, count = 3)] //! struct FirstObject; //! //! // `expr` can be specified multiple times because of the `append` attribute //! #[derive(MyObject)] //! #[my_object(object_id = 2, name = "Second", expr = 1 + 2, expr = 3 + 4)] //! struct SecondObject; //! //! // `unknown` and `extra` will be stored in the `rest` hashmap //! #[derive(MyObject)] //! #[my_object(id = 3, name = "Third", unknown = 1 + 2, extra = 3 + 4)] //! struct ThirdObject; //! ``` //! //! #### Inheritance //! //! The [`flatten`](macro@ParseMetaItem#deluxeflatten-1) attribute can be used to parse keys from //! one structure inside another: //! //! ``` //! #[derive(deluxe::ParseMetaItem)] //! struct A { //! id: u64, //! } //! //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(b))] //! struct B { //! #[deluxe(flatten)] //! a: A, //! name: String, //! } //! ``` //! //! Then, fields from both `A` and `B` can be used when deriving `B`: //! //! ```ignore //! #[derive(B)] //! #[b(id = 123, name = "object")] //! struct Object; //! ``` //! //! #### Attributes in Nested Code //! //! Extra attributes can be taken from within the code block attached to a macro. When used in an //! attribute macro, the attributes should be consumed so as not to produce an "unknown attribute" //! error when outputting tokens. //! //! ``` //! #[derive(deluxe::ParseMetaItem, deluxe::ExtractAttributes)] //! struct MyDescription { //! name: String, //! version: String, //! } //! //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(author))] //! struct Authors(#[deluxe(flatten)] Vec); //! //! fn my_derive(item: proc_macro2::TokenStream) -> deluxe::Result { //! let mut input = syn::parse2::(item)?; //! let MyDescription { name, version } = deluxe::extract_attributes(&mut input)?; //! let mut authors = Vec::new(); //! if let syn::Data::Struct(s) = &mut input.data { //! // Look through all fields in the struct for `author` attributes //! for field in s.fields.iter_mut() { //! let Authors(a) = deluxe::extract_attributes(field)?; //! authors.extend(a); //! } //! } //! //! let ident = &input.ident; //! let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl(); //! //! Ok(quote::quote! { //! impl #impl_generics #ident #type_generics #where_clause { //! fn my_desc() -> &'static str { //! concat!("Name: ", #name, ", Version: ", #version #(, ", Author: ", #authors)*) //! } //! } //! }) //! } //! //! # let tokens = my_derive(quote::quote! { //! # #[my_desc(name = "hello world", version = "0.2")] //! # struct Hello(#[author("Alice")] String); //! # }).unwrap(); //! # let i: syn::ItemImpl = syn::parse_quote! { #tokens }; //! # assert_eq!(i, syn::parse_quote! { //! # impl Hello { //! # fn my_desc() -> &'static str { //! # concat!("Name: ", "hello world", ", Version: ", "0.2", ", Author: ", "Alice") //! # } //! # } //! # }); //! //! fn my_desc_mod( //! attr: proc_macro2::TokenStream, //! item: proc_macro2::TokenStream, //! ) -> deluxe::Result { //! let MyDescription { name, version } = deluxe::parse2::(attr)?; //! let mut authors = Vec::new(); //! let mut module = syn::parse2::(item)?; //! //! let (_, items) = module.content.as_mut().unwrap(); //! //! // Look through all items in the module for `author` attributes //! for i in items.iter_mut() { //! // Extract the attributes to remove them from the final output //! let Authors(a) = deluxe::extract_attributes(i)?; //! authors.extend(a); //! } //! //! // Place a new function inside the module //! items.push(syn::parse_quote! { //! fn my_desc() -> &'static str { //! concat!("Name: ", #name, ", Version: ", #version #(, ", Author: ", #authors)*) //! } //! }); //! //! Ok(quote::quote! { #module }) //! } //! //! # let tokens = my_desc_mod( //! # quote::quote!(name = "hello world", version = "0.2"), //! # quote::quote!(mod abc { //! # #[author("Alice", "Bob")] //! # fn func1() {} //! # #[author("Carol")] //! # #[author("Dave")] //! # fn func2() {} //! # }), //! # ).unwrap(); //! # let m: syn::ItemMod = syn::parse_quote! { #tokens }; //! # assert_eq!(m, syn::parse_quote! { //! # mod abc { //! # fn func1() {} //! # fn func2() {} //! # fn my_desc() -> &'static str { //! # concat!( //! # "Name: ", "hello world", ", Version: ", "0.2", //! # ", Author: ", "Alice", ", Author: ", "Bob", //! # ", Author: ", "Carol", ", Author: ", "Dave" //! # ) //! # } //! # } //! # }); //! ``` //! //! ```ignore //! // In your normal code //! //! #[derive(MyDescription, Default)] //! #[my_desc(name = "hello world", version = "0.2")] //! struct Hello { //! #[author("Alice")] //! a: i32, //! #[author("Bob")] //! b: String //! } //! //! let hello: Hello = Default::default(); //! assert_eq!(hello.my_desc(), "Name: hello world, Version: 0.2, Author: Alice, Author: Bob"); //! //! #[my_desc_mod(name = "hello world", version = "0.2")] //! mod abc { //! #[author("Alice", "Bob")] //! fn func1() {} //! //! #[author("Carol")] //! #[author("Dave")] //! fn func2() {} //! } //! //! assert_eq!( //! abc::my_desc(), //! "Name: hello world, Version: 0.2, Author: Alice, Author: Bob, Author: Carol, Author: Dave" //! ); //! ``` //! //! #### Tuple Structs, Tuples and Vecs //! //! Deluxe also supports parsing into data structures with unnamed fields. //! //! ``` //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_tuple))] //! struct MyTuple(u64, String); //! //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_idents))] //! struct MyIdents { //! id: u64, //! names: (String, String), //! idents: Vec //! } //! ``` //! //! The standard attribute syntax with parenthesis can be used when specifying a [`Vec`] type. The //! alternative syntax `key = [...]` can also be used to have an appearance similar to an array //! literal. //! //! ```ignore //! #[derive(MyTuple)] //! #[my_tuple(123, "object")] //! struct Object; //! //! #[derive(MyIdents)] //! #[my_idents(id = 7, names("hello", "world"), idents(a, b, c))] //! struct ABC; //! //! // `idents` contains same values as above //! #[derive(MyIdents)] //! #[my_idents(id = 7, names("hello", "world"), idents = [a, b, c])] //! struct ABC2; //! ``` //! //! #### C#-styled Attributes //! //! Attributes in C# can support positional arguments first with the named //! arguments afterwards. This style can be emulated by using a tuple struct with a //! normal struct flattened at the end. Placing //! [`#[deluxe(default)]`](macro@ParseMetaItem#deluxedefault) on the struct behaves the same as //! Serde, by filling in all fields with values from [`Default`], allowing every named argument to //! be optional. //! //! ``` //! #[derive(deluxe::ParseMetaItem, Default)] //! #[deluxe(default)] //! struct Flags { //! native: bool, //! } //! //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(a))] //! struct A(u64, String, #[deluxe(flatten)] Flags); //! ``` //! //! ```ignore //! #[derive(A)] //! #[a(123, "object")] //! struct Object; //! //! #[derive(A)] //! #[a(123, "native-object", native = true)] //! struct NativeObject; //! ``` //! //! #### Enums //! //! Enums are supported by using the variant name as a single key, in snake-case. Variants can be //! renamed, aliased and skipped in the same way as fields. //! //! ``` //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_enum))] //! enum MyEnum { //! A, //! B, //! C, //! #[deluxe(alias = d)] //! AnotherOne, //! #[deluxe(rename = e)] //! AnotherTwo, //! #[deluxe(skip)] //! SkipMe //! } //! ``` //! //! ```ignore //! #[derive(MyEnum)] //! #[my_enum(b)] //! struct ObjectB; //! //! #[derive(MyEnum)] //! #[my_enum(another_one)] //! struct ObjectD; //! ``` //! //! #### Complex Enums //! //! Enums with struct and tuple variants are also supported. The data inside is used as arguments //! to the attribute. All field attributes from structs are also supported inside variants. //! //! Additionally, enum variants with named fields can be flattened. The behavior of a flattened //! variant is similar to Serde's `untagged` mode. In a flattened variant, the name of the variant //! will be ignored. Instead, Deluxe will attempt to use the unique keys in each variant to //! determine if that variant was specified. A compile error will be thrown if it is not possible //! to determine a unique, unambiguous key between two variants. //! //! ``` //! #[derive(deluxe::ExtractAttributes)] //! #[deluxe(attributes(my_enum))] //! enum MyEnum { //! A, //! B(u64, String), //! C { id: u64, name: String }, //! #[deluxe(flatten)] //! D { d: u64, name: String }, //! } //! ``` //! //! ```ignore //! #[derive(MyEnum)] //! #[my_enum(a)] //! struct ObjectA; //! //! #[derive(MyEnum)] //! #[my_enum(b(1, "hello"))] //! struct ObjectB; //! //! #[derive(MyEnum)] //! #[my_enum(c(id = 2, name = "world"))] //! struct ObjectC; //! //! // No inner parenthesis needed here due to flattening //! #[derive(MyEnum)] //! #[my_enum(d = 3, name = "moon")] //! struct ObjectD; //! ``` //! //! #### Storing Containers //! //! During parsing, Deluxe can store references to the container type holding the attributes for //! easier access. Container fields are skipped during attribute parsing. //! //! ``` //! #[derive(deluxe::ParseAttributes)] //! #[deluxe(attributes(my_object))] //! struct MyObject<'t> { //! id: u64, //! // Fill `container` in using the parsed type. Note this restricts the //! // derived `ParseAttributes` impl so it can only be used on `DeriveInput`. //! #[deluxe(container)] //! container: &'t syn::DeriveInput, //! } //! //! fn my_object(item: proc_macro2::TokenStream) -> deluxe::Result { //! let input = syn::parse2::(item)?; //! //! // `obj.container` now holds a reference to `input` //! let obj: MyObject = deluxe::parse_attributes(&input)?; //! //! Ok(quote::quote! { /* ... generate some code here ... */ }) //! } //! ``` //! //! To support both extracting and parsing, a container field can also be a value type. In that //! case, the container will be cloned into the structure. #![deny(missing_docs)] #![deny(unsafe_code)] #[doc(hidden)] pub mod ____private { pub use deluxe_core::parse_helpers::{self, FieldStatus, SmallString}; pub use once_cell::sync::OnceCell as SyncOnceCell; pub use proc_macro2::Span; pub use std::{ borrow::{Borrow, Cow, ToOwned}, clone::Clone, collections::HashMap, convert::{AsRef, From}, default::Default, format, format_args, iter::IntoIterator, option::Option, primitive::{bool, str, usize}, string::{String, ToString}, unreachable, vec::Vec, }; pub use syn::{ parse::{ParseBuffer, ParseStream}, Error, Ident, Path, }; } pub use deluxe_core::{ define_with_collection, define_with_map, define_with_optional, parse_named_meta_item_with, with, Error, Errors, ExtractAttributes, Flag, HasAttributes, ParseAttributes, ParseMetaItem, ParseMode, Result, SpannedValue, }; #[doc(hidden)] pub use deluxe_core::{ ContainerFrom, ParseMetaAppend, ParseMetaFlatNamed, ParseMetaFlatUnnamed, ParseMetaRest, ToKeyString, }; pub use deluxe_macros::*; /// Additional helper functions for validating after parsing. pub mod validations { pub use deluxe_core::validations::*; pub use deluxe_core::{all_or_none, only_one}; } #[cfg(feature = "proc-macro")] extern crate proc_macro; /// Parses a required Rust type out of a token stream. /// /// Intended for use with [attribute /// macros](https://doc.rust-lang.org/stable/reference/procedural-macros.html#attribute-macros). /// This is a small wrapper around [`syn::parse::Parser::parse`] and /// [`ParseMetaItem::parse_meta_item_inline`]. #[cfg(feature = "proc-macro")] #[inline] pub fn parse(attr: proc_macro::TokenStream) -> Result { syn::parse::Parser::parse( |stream: syn::parse::ParseStream<'_>| { T::parse_meta_item_inline(&[stream], ParseMode::Named(proc_macro2::Span::call_site())) }, attr, ) } /// Parses a required Rust type out of a token stream. /// /// Intended for use with [attribute /// macros](https://doc.rust-lang.org/stable/reference/procedural-macros.html#attribute-macros). /// This is a small wrapper around [`syn::parse::Parser::parse2`] and /// [`ParseMetaItem::parse_meta_item_inline`]. #[inline] pub fn parse2(attr: proc_macro2::TokenStream) -> Result { syn::parse::Parser::parse2( |stream: syn::parse::ParseStream<'_>| { T::parse_meta_item_inline(&[stream], ParseMode::Named(proc_macro2::Span::call_site())) }, attr, ) } /// Parses a required Rust type out of another type holding a list of [`syn::Attribute`]. /// /// Intended for use with [derive /// macros](https://doc.rust-lang.org/stable/reference/procedural-macros.html#derive-macros). This /// is a small wrapper around [`ParseAttributes::parse_attributes`]. #[inline] pub fn parse_attributes<'t, T, R>(obj: &'t T) -> Result where T: HasAttributes, R: ParseAttributes<'t, T>, { R::parse_attributes(obj) } /// Extracts attributes out of another type holding a list of [`syn::Attribute`], then parses them /// into a required Rust type. /// /// Intended for use with [derive /// macros](https://doc.rust-lang.org/stable/reference/procedural-macros.html#derive-macros). This /// is a small wrapper around [`ExtractAttributes::extract_attributes`]. #[inline] pub fn extract_attributes(obj: &mut T) -> Result where T: HasAttributes, R: ExtractAttributes, { R::extract_attributes(obj) } /// Parses a Rust type out of a token stream, returning a default value on failure. /// /// Calls [`parse`] and returns the result. Upon failure, [`Default::default`] will be returned and /// any errors will be appended to `errors`. This function should be preferred when parsing /// multiple attributes, so the errors from all of them can be accumulated instead of returning /// early. #[cfg(feature = "proc-macro")] #[inline] pub fn parse_optional( attr: proc_macro::TokenStream, errors: &Errors, ) -> T { match parse(attr) { Ok(t) => t, Err(e) => { errors.push_syn(e); Default::default() } } } /// Parses a Rust type out of a token stream, returning a default value on failure. /// /// Calls [`parse2`] and returns the result. Upon failure, [`Default::default`] will be returned /// and any errors will be appended to `errors`. This function should be preferred when parsing /// multiple attributes, so the errors from all of them can be accumulated instead of returning /// early. #[inline] pub fn parse2_optional( attr: proc_macro2::TokenStream, errors: &Errors, ) -> T { match parse2(attr) { Ok(t) => t, Err(e) => { errors.push_syn(e); Default::default() } } } /// Parses a Rust type out of another type holding a list of [`syn::Attribute`], returning a default value on failure. /// /// Calls [`parse_attributes`] and returns the result. Upon failure, [`Default::default`] will be /// returned and any errors will be appended to `errors`. This function should be preferred when /// parsing multiple attributes, so the errors from all of them can be accumulated instead of /// returning early. #[inline] pub fn parse_attributes_optional<'t, T, R>(obj: &'t T, errors: &Errors) -> R where T: HasAttributes, R: ParseAttributes<'t, T> + Default, { match parse_attributes(obj) { Ok(t) => t, Err(e) => { errors.push_syn(e); Default::default() } } } /// Extracts attributes out of another type holding a list of [`syn::Attribute`], then parses them /// into a Rust type, returning a default value on failure. /// /// Calls [`extract_attributes`] and returns the result. Upon failure, [`Default::default`] will be /// returned and any errors will be appended to `errors`. This function should be preferred when /// parsing multiple attributes, so the errors from all of them can be accumulated instead of /// returning early. #[inline] pub fn extract_attributes_optional(obj: &mut T, errors: &Errors) -> R where T: HasAttributes, R: ExtractAttributes + Default, { match extract_attributes(obj) { Ok(t) => t, Err(e) => { errors.push_syn(e); Default::default() } } } deluxe-0.5.0/tests/attributes.rs000064400000000000000000000332371046102023000150220ustar 00000000000000#![deny(unsafe_code)] #![no_implicit_prelude] use ::quote::quote as q; mod test_util; use test_util::*; #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(single))] struct SingleAttribute(char); #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(single))] struct SingleAttributeNamed { c: char, } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(multi1, multi2))] struct MultiAttributes(char); #[test] fn multi_attributes() { use ::deluxe::HasAttributes; let expr: ::syn::Expr = ::syn::parse2(q! { #[single('a')] true }).unwrap(); let m: SingleAttribute = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 1); ::std::assert_eq!(m.0, 'a'); let expr: ::syn::Expr = ::syn::parse2(q! { #[single(c = 'a')] true }).unwrap(); let m: SingleAttributeNamed = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 1); ::std::assert_eq!(m.c, 'a'); let expr: ::syn::Expr = ::syn::parse2(q! { true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, SingleAttribute>(&expr).unwrap_err_string(), "missing required field 0 on #[single]" ); let expr: ::syn::Expr = ::syn::parse2(q! { #[single] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, SingleAttribute>(&expr).unwrap_err_string(), "missing required field 0 on #[single]" ); let expr: ::syn::Expr = ::syn::parse2(q! { true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, SingleAttributeNamed>(&expr).unwrap_err_string(), "missing required field #[single(c)]" ); let expr: ::syn::Expr = ::syn::parse2(q! { #[single] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, SingleAttributeNamed>(&expr).unwrap_err_string(), "missing required field #[single(c)]" ); let expr: ::syn::Expr = ::syn::parse2(q! { #[multi1('a')] true }).unwrap(); let m: MultiAttributes = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 1); ::std::assert_eq!(m.0, 'a'); let expr: ::syn::Expr = ::syn::parse2(q! { #[multi2('b')] true }).unwrap(); let m: MultiAttributes = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 1); ::std::assert_eq!(m.0, 'b'); let expr = ::syn::parse2(q! { true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "missing required field 0 on #[multi1]" ); let expr = ::syn::parse2(q! { #[multi1()] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "missing required field 0 on #[multi1]" ); let expr = ::syn::parse2(q! { #[multi2()] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "missing required field 0 on #[multi2]" ); let expr = ::syn::parse2(q! { #[multi2] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "missing required field 0 on #[multi2]" ); let expr = ::syn::parse2(q! { #[multi3('c')] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "missing required field 0 on #[multi1]" ); let expr = ::syn::parse2(q! { #[multi2('c')] #[multi2('d')] true }).unwrap(); ::std::assert_eq!( ::deluxe::parse_attributes::<::syn::Expr, MultiAttributes>(&expr).unwrap_err_string(), "unexpected token" ); } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(many))] struct Many(i32, i32, i32, i32, i32, i32); #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(many), transparent)] struct ManyVec(::std::vec::Vec); #[test] fn split_attributes() { let expr: ::syn::Expr = ::syn::parse2(q! { #[many(1)] #[many(2, 3)] #[many(4, 5, 6)] true }).unwrap(); let m: Many = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(m, Many(1, 2, 3, 4, 5, 6)); let expr: ::syn::Expr = ::syn::parse2(q! { #[many(1)] #[many(2, 3)] #[many(4, 5, 6)] true }).unwrap(); let m: ManyVec = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(m, ManyVec(::std::vec![1, 2, 3, 4, 5, 6])); } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(container::clone))] struct CloneContainer { #[deluxe(container)] container: ::syn::Expr, int: i32, } #[test] fn clone_container() { use ::deluxe::HasAttributes; let mut expr = ::syn::parse2(q! { #[container::ignored(int = 4)] #[container::clone(int = 2)] true }) .unwrap(); let cont: CloneContainer = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 2); ::std::assert_eq!(cont.container, expr); ::std::assert_eq!(cont.int, 2); let cont2: CloneContainer = ::deluxe::extract_attributes(&mut expr).unwrap(); ::std::assert_eq!(expr.attrs().len(), 1); ::std::assert_eq!(cont2.container, expr); ::std::assert_eq!(cont2.int, 2); ::std::assert_ne!(cont.container, cont2.container); } #[derive(::deluxe::ParseAttributes, PartialEq, Debug)] #[deluxe(attributes(container::r#ref))] struct RefContainer<'e> { #[deluxe(container)] container: &'e ::syn::Expr, int: i32, } #[test] fn ref_container() { let expr = ::syn::parse2(q! { #[container::r#ref(int = 3)] true }).unwrap(); let cont: RefContainer = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container, &expr); ::std::assert_eq!(cont.int, 3); } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(container::clone_generic))] struct CloneGenericContainer { #[deluxe(container)] container: T, int: i32, } #[test] fn clone_generic_container() { let mut expr = ::syn::parse2(q! { #[container::clone_generic(int = 4)] true }).unwrap(); let cont: CloneGenericContainer<::syn::Expr> = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container, expr); ::std::assert_eq!(cont.int, 4); let cont2: CloneGenericContainer<::syn::Expr> = ::deluxe::extract_attributes(&mut expr).unwrap(); ::std::assert_eq!(cont2.container, expr); ::std::assert_eq!(cont2.int, 4); } #[derive(::deluxe::ParseAttributes, PartialEq, Debug)] #[deluxe(attributes(container::ref_generic))] struct RefGenericContainer<'t, T> { #[deluxe(container)] container: &'t T, int: i32, } #[test] fn ref_generic_container() { let expr = ::syn::parse2(q! { #[container::ref_generic(int = 5)] true }).unwrap(); let cont: RefGenericContainer<::syn::Expr> = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container, &expr); ::std::assert_eq!(cont.int, 5); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(attributes(container::clone_option))] struct CloneOptionContainer { #[deluxe(container, default)] container: ::std::option::Option<::syn::Expr>, int: i32, } #[test] fn clone_option_container() { let mut expr = ::syn::parse2(q! { #[container::clone_option(int = 6)] true }).unwrap(); let cont: CloneOptionContainer = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container.unwrap(), expr); ::std::assert_eq!(cont.int, 6); let cont2: CloneOptionContainer = ::deluxe::extract_attributes(&mut expr).unwrap(); ::std::assert_eq!(cont2.container, ::std::option::Option::Some(expr)); ::std::assert_eq!(cont2.int, 6); } #[derive(::deluxe::ParseAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug)] #[deluxe(attributes(container::ref_option))] struct RefOptionContainer<'e> { #[deluxe(container, default)] container: ::std::option::Option<&'e ::syn::Expr>, int: i32, } #[test] fn ref_option_container() { let expr = ::syn::parse2(q! { #[container::ref_option(int = 7)] true }).unwrap(); let cont: RefOptionContainer = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container, ::std::option::Option::Some(&expr)); ::std::assert_eq!(cont.int, 7); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(attributes(container::clone_generic_option))] struct CloneGenericOptionContainer { #[deluxe(container, default)] container: ::std::option::Option, int: i32, } #[test] fn clone_generic_option_container() { let mut expr = ::syn::parse2(q! { #[container::clone_generic_option(int = 8)] true }).unwrap(); let cont: CloneGenericOptionContainer<::syn::Expr> = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container.unwrap(), expr); ::std::assert_eq!(cont.int, 8); let cont2: CloneGenericOptionContainer<::syn::Expr> = ::deluxe::extract_attributes(&mut expr).unwrap(); ::std::assert_eq!(cont2.container, ::std::option::Option::Some(expr)); ::std::assert_eq!(cont2.int, 8); } #[derive(::deluxe::ParseAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug)] #[deluxe(attributes(container::ref_generic_option))] struct RefGenericOptionContainer<'t, T> { #[deluxe(container, default)] container: ::std::option::Option<&'t T>, int: i32, } #[test] fn ref_generic_option_container() { let expr = ::syn::parse2(q! { #[container::ref_generic_option(int = 9)] true }).unwrap(); let cont: RefGenericOptionContainer<::syn::Expr> = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert_eq!(cont.container, ::std::option::Option::Some(&expr)); ::std::assert_eq!(cont.int, 9); } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, PartialEq, Debug)] #[deluxe(attributes(container::an_enum))] enum ContainerEnum { A(#[deluxe(container)] ::syn::Expr, #[deluxe(skip)] i32, i32), B { #[deluxe(container)] container: ::syn::Expr, #[deluxe(skip)] skipped: i32, value: i32, }, #[deluxe(flatten)] C { #[deluxe(container)] container: ::syn::Expr, #[deluxe(skip)] skipped: i32, c: i32, }, #[deluxe(flatten)] D { #[deluxe(container)] container: ::syn::Expr, #[deluxe(skip)] skipped: i32, }, } #[test] fn container_enum() { let expr: ::syn::Expr = ::syn::parse2(q! { #[container::an_enum(a(500))] true }) .unwrap(); let cont: ContainerEnum = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert!(::std::matches!(cont, ContainerEnum::A(e, 0, 500) if e == expr)); let expr: ::syn::Expr = ::syn::parse2(q! { #[container::an_enum(b(value = 501))] true }) .unwrap(); let cont: ContainerEnum = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert!( ::std::matches!(cont, ContainerEnum::B { container: e, skipped: 0, value: 501 } if e == expr) ); let expr: ::syn::Expr = ::syn::parse2(q! { #[container::an_enum(c = 502)] true }) .unwrap(); let cont: ContainerEnum = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert!( ::std::matches!(cont, ContainerEnum::C { container: e, skipped: 0, c: 502 } if e == expr) ); let expr: ::syn::Expr = ::syn::parse2(q! { #[container::an_enum()] true }) .unwrap(); let cont: ContainerEnum = ::deluxe::parse_attributes(&expr).unwrap(); ::std::assert!( ::std::matches!(cont, ContainerEnum::D { container: e, skipped: 0 } if e == expr) ); } #[derive(Debug, PartialEq)] struct IdentWrapper<'t>(&'t ::syn::Ident); impl<'t> ::deluxe::ContainerFrom<'t, ::syn::ItemFn> for IdentWrapper<'t> { #[inline] fn container_from(t: &'t ::syn::ItemFn) -> Self { Self(&t.sig.ident) } } #[derive(::deluxe::ParseAttributes, PartialEq, Debug)] #[deluxe(attributes(container::wrapper))] struct WrapperContainer<'t> { #[deluxe(container(ty = ::syn::ItemFn))] container: IdentWrapper<'t>, int: i32, } #[derive(Debug, PartialEq)] struct Ident2Wrapper<'s, 't>(::std::borrow::Cow<'s, str>, &'t ::syn::Ident); impl<'s, 't> ::deluxe::ContainerFrom<'t, ::syn::ItemFn> for Ident2Wrapper<'s, 't> { #[inline] fn container_from(t: &'t ::syn::ItemFn) -> Self { Self(::std::convert::From::from("hello"), &t.sig.ident) } } #[derive(::deluxe::ParseAttributes, PartialEq, Debug)] #[deluxe(attributes(container::wrapper))] struct Wrapper2Container<'s, 't> { #[deluxe(container(ty = ::syn::ItemFn, lifetime = 't))] container: Ident2Wrapper<'s, 't>, int: i32, } #[test] fn custom_container() { use ::deluxe::HasAttributes; let func: ::syn::ItemFn = ::syn::parse2(q! { #[container::wrapper(int = 72)] fn abc() -> i32 { 0 } }) .unwrap(); let cont: WrapperContainer = ::deluxe::parse_attributes(&func).unwrap(); ::std::assert_eq!(func.attrs().len(), 1); ::std::assert_eq!(cont.container.0, &func.sig.ident); ::std::assert_eq!(cont.int, 72); let cont: Wrapper2Container = ::deluxe::parse_attributes(&func).unwrap(); ::std::assert_eq!(func.attrs().len(), 1); ::std::assert_eq!(cont.container.0, "hello"); ::std::assert_eq!(cont.container.1, &func.sig.ident); ::std::assert_eq!(cont.int, 72); } deluxe-0.5.0/tests/meta.rs000064400000000000000000001527211046102023000135620ustar 00000000000000#![deny(unsafe_code)] #![no_implicit_prelude] use ::quote::quote as q; mod test_util; use test_util::*; #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyUnit; #[test] fn parse_unit() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { () }).unwrap(), MyUnit); ::std::assert_eq!( parse(q! { (1) }).unwrap_err_string(), "unexpected token `1`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyUnnamedEmpty(); #[test] fn parse_unnamed_empty() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { () }).unwrap(), MyUnnamedEmpty()); ::std::assert_eq!( parse(q! { (1) }).unwrap_err_string(), "unexpected token `1`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent)] struct MyNewtype(::std::string::String); #[test] fn parse_newtype() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { "qwerty" }).unwrap(), MyNewtype("qwerty".into())); ::std::assert_eq!( parse(q! { 123 }).unwrap_err_string(), "expected string literal" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyUnnamed(i32, ::std::string::String); #[test] fn parse_unnamed() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { (123, "abc") }).unwrap(), MyUnnamed(123, "abc".into()) ); ::std::assert_eq!( parse(q! { (123) }).unwrap_err_string(), "missing required field 1" ); ::std::assert_eq!( parse(q! { (123, "abc", true) }).unwrap_err_string(), "unexpected token `true`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamedEmpty {} #[test] fn parse_named_empty() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { {} }).unwrap(), MyNamedEmpty {}); ::std::assert_eq!( parse(q! { {a = 123} }).unwrap_err_string(), "unknown field `a`" ); ::std::assert_eq!(parse_flag::().unwrap(), MyNamedEmpty {}); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamed { a: i32, b: ::std::string::String, } #[test] fn parse_named() { use ::std::prelude::v1::*; let parse = parse_meta::; let t = MyNamed { a: 123, b: "asdf".into(), }; ::std::assert_eq!(parse(q! { {a = 123, b = "asdf"} }).unwrap(), t); ::std::assert_eq!(parse(q! { {a(123), b = "asdf"} }).unwrap(), t); ::std::assert_eq!(parse(q! { {a = 123, b("asdf")} }).unwrap(), t); ::std::assert_eq!(parse(q! { {a(123), b("asdf")} }).unwrap(), t); ::std::assert_eq!( parse(q! { {} }).unwrap_err_string(), "missing required field `a`, missing required field `b`" ); ::std::assert_eq!( parse(q! { {b("asdf")} }).unwrap_err_string(), "missing required field `a`" ); ::std::assert_eq!( parse(q! { {a(123)} }).unwrap_err_string(), "missing required field `b`" ); ::std::assert_eq!( parse(q! { {a(123), b("asdf"), c(true)} }).unwrap_err_string(), "unknown field `c`" ); ::std::assert_eq!( parse(q! { {a(123), b("asdf"), a(456)} }).unwrap_err_string(), "duplicate attribute for `a`" ); ::std::assert_eq!( parse(q! { {a(123), b("asdf"), a(456), a("456") } }).unwrap_err_string(), "duplicate attribute for `a`, duplicate attribute for `a`, expected integer literal" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamedChild { c: i32, #[deluxe(flatten)] d: MyNamed, } #[test] fn parse_named_flat() { use ::std::prelude::v1::*; let parse = parse_meta::; let t = MyNamedChild { c: 900, d: MyNamed { a: 100, b: "qwerty".into(), }, }; ::std::assert_eq!(parse(q! { {a = 100, b = "qwerty", c = 900} }).unwrap(), t); ::std::assert_eq!( parse(q! { {} }).unwrap_err_string(), "missing required field `a`, missing required field `b`, missing required field `c`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamedChildPrefixed { c: i32, #[deluxe(flatten(prefix = d))] d: MyNamed, } #[test] fn parse_named_flat_prefixed() { use ::std::prelude::v1::*; let parse = parse_meta::; let t = MyNamedChildPrefixed { c: 900, d: MyNamed { a: 100, b: "qwerty".into(), }, }; ::std::assert_eq!( parse(q! { {d::a = 100, d::b = "qwerty", c = 900} }).unwrap(), t ); ::std::assert_eq!( parse(q! { {} }).unwrap_err_string(), "missing required field `d::a`, missing required field `d::b`, missing required field `c`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamedChildLongPrefixed { c: i32, #[deluxe(flatten(prefix = d::e))] d: MyNamed, #[deluxe(flatten(prefix = d::e2))] d2: MyNamed, } #[test] fn parse_named_flat_long_prefixed() { use ::std::prelude::v1::*; let parse = parse_meta::; let t = MyNamedChildLongPrefixed { c: 900, d: MyNamed { a: 100, b: "qwerty".into(), }, d2: MyNamed { a: 200, b: "uiop".into(), }, }; ::std::assert_eq!( parse( q! { {d::e::a = 100, d::e::b = "qwerty", d::e2::b = "uiop", d::e2::a = 200, c = 900} } ) .unwrap(), t ); ::std::assert_eq!( parse(q! { {} }).unwrap_err_string(), "missing required field `d::e::a`, missing required field `d::e::b`, \ missing required field `d::e2::a`, missing required field `d::e2::b`, \ missing required field `c`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyNamedComplex { idents: ::std::vec::Vec<::syn::Ident>, #[deluxe(skip)] skipped: bool, #[deluxe(append)] exprs: ::std::vec::Vec<::syn::Expr>, #[deluxe(rest)] rest: ::std::collections::HashMap<::syn::Path, ::syn::Expr>, } #[test] fn vec_field() { use ::std::prelude::v1::*; fn cs() -> ::proc_macro2::Span { ::proc_macro2::Span::call_site() } let parse = parse_meta::; ::std::assert_eq!( parse(q! { { } }).unwrap_err_string(), "missing required field `idents`" ); ::std::assert_eq!( parse(q! { { idents } }).unwrap_err_string(), "unexpected flag, expected `=` or parentheses" ); ::std::assert_eq!( parse(q! { { idents = [] } }).unwrap().idents, &[] as &[::syn::Ident] ); ::std::assert_eq!( parse(q! { { idents() } }).unwrap().idents, &[] as &[::syn::Ident] ); let hello_world = &[ ::syn::Ident::new("hello", cs()), ::syn::Ident::new("world", cs()), ]; ::std::assert_eq!( parse(q! { { idents = [hello, world] } }).unwrap().idents, hello_world, ); ::std::assert_eq!( parse(q! { { idents = [hello, world,] } }).unwrap().idents, hello_world, ); ::std::assert_eq!( parse(q! { { idents(hello, world) } }).unwrap().idents, hello_world, ); ::std::assert_eq!( parse(q! { { idents(hello, world,) } }).unwrap().idents, hello_world, ); ::std::assert_eq!( parse(q! { { idents = (hello, world) } }).unwrap_err_string(), "expected square brackets" ); ::std::assert_eq!( parse(q! { { idents = [hello world] } }).unwrap_err_string(), "expected `,`" ); ::std::assert_eq!( parse(q! { { idents = [hello, 123, world] } }).unwrap_err_string(), "expected ident" ); ::std::assert_eq!( parse(q! { { idents = [hello, 123, world, 456, moon] } }).unwrap_err_string(), "expected ident, expected ident" ); } #[test] fn skipped_field_rest() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert!(!parse(q! { { idents = [] } }).unwrap().skipped); ::std::assert_eq!( parse(q! { { idents = [], skipped = true } }).unwrap(), MyNamedComplex { idents: ::std::vec![], skipped: false, exprs: ::std::vec![], rest: [( ::syn::parse_quote! { skipped }, ::syn::parse_quote! { true }, )] .into_iter() .collect(), }, ); } impl MyNamedComplex { #[inline] fn exprs_str(&self) -> ::std::string::String { use ::quote::ToTokens; use ::std::prelude::v1::*; self.exprs .iter() .map(|e| ::std::format!("({})", e.to_token_stream())) .collect::>() .join(", ") } #[inline] fn rest_str(&self) -> ::std::string::String { use ::quote::ToTokens; use ::std::prelude::v1::*; let mut rest = self.rest.iter().collect::>(); rest.sort_by_key(|(k, _)| k.to_token_stream().to_string()); rest.into_iter() .map(|(k, v)| ::std::format!("({} => {})", k.to_token_stream(), v.to_token_stream())) .collect::>() .join(", ") } } #[test] fn struct_append() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { { idents = [] } }).unwrap().exprs, []); ::std::assert_eq!( parse(q! { { idents = [], exprs = {} } }) .unwrap() .exprs_str(), "({ })", ); ::std::assert_eq!( parse(q! { { idents = [], exprs = {}, exprs = 123 + 4 } }) .unwrap() .exprs_str(), "({ }), (123 + 4)", ); ::std::assert_eq!( parse(q! { { idents = [], exprs = ! } }).unwrap_err_string(), "unexpected end of input, expected expression" ); } #[test] fn struct_rest() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { { idents = [] } }).unwrap().exprs, []); ::std::assert_eq!( parse(q! { { idents = [], abcd = 123 + 4 } }) .unwrap() .rest_str(), "(abcd => 123 + 4)", ); ::std::assert_eq!( parse(q! { { idents = [], abcd = 123 + 4, hello::world = { "str" } } }) .unwrap() .rest_str(), r#"(abcd => 123 + 4), (hello :: world => { "str" })"#, ); ::std::assert_eq!( parse(q! { { idents = [], abcd = 123 + 4, hello::world = { "str" }, exprs = 126 - 5 } }) .unwrap() .rest_str(), r#"(abcd => 123 + 4), (hello :: world => { "str" })"#, ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyUnnamedRest(i32, #[deluxe(flatten)] ::std::vec::Vec); #[test] fn tuple_struct_rest() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { () }).unwrap_err_string(), "missing required field 0" ); ::std::assert_eq!(parse(q! { (1) }).unwrap(), MyUnnamedRest(1, Vec::new())); ::std::assert_eq!( parse(q! { (1, 2) }).unwrap(), MyUnnamedRest(1, ::std::vec![2]) ); ::std::assert_eq!( parse(q! { (1, 2,) }).unwrap(), MyUnnamedRest(1, ::std::vec![2]) ); ::std::assert_eq!( parse(q! { (1, 2, 3, 4) }).unwrap(), MyUnnamedRest(1, ::std::vec![2, 3, 4]) ); ::std::assert_eq!( parse(q! { (1, 2, 3, 4, "hello", 6) }).unwrap_err_string(), "expected integer literal" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum MyEmptyEnum {} #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyFlatNamed { j_a: i32, j_b: ::std::string::String, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum MyEnum { A, B(), C(i32), #[deluxe(transparent)] D(bool), E(::std::string::String, f64), F {}, #[deluxe(transparent)] G { pass: ::syn::Path, }, H { s: ::std::string::String, f: f64, }, #[deluxe(flatten)] FlatI { i: ::std::string::String, }, #[deluxe(flatten)] FlatJ { #[deluxe(flatten)] named: MyFlatNamed, }, #[deluxe(skip)] #[allow(dead_code)] K, } #[test] fn parse_enum() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { ( a ) }).unwrap_err_string(), "expected curly braces" ); ::std::assert_eq!(parse(q! { { a } }).unwrap(), MyEnum::A); ::std::assert_eq!(parse(q! { { a() } }).unwrap(), MyEnum::A); ::std::assert_eq!( parse(q! { { a(x = 123) } }).unwrap_err_string(), "unexpected token `x`" ); ::std::assert_eq!(parse(q! { { b() } }).unwrap(), MyEnum::B()); ::std::assert_eq!(parse(q! { { b = () } }).unwrap(), MyEnum::B()); ::std::assert_eq!( parse(q! { { b(x = 123) } }).unwrap_err_string(), "unexpected token `x`" ); ::std::assert_eq!(parse(q! { { c(123) } }).unwrap(), MyEnum::C(123)); ::std::assert_eq!( parse(q! { { c } }).unwrap_err_string(), "unexpected flag, expected `=` or parentheses" ); ::std::assert_eq!( parse(q! { { c = 123 } }).unwrap_err_string(), "expected parentheses" ); ::std::assert_eq!(parse(q! { { d(true) } }).unwrap(), MyEnum::D(true)); ::std::assert_eq!(parse(q! { { d = true } }).unwrap(), MyEnum::D(true)); ::std::assert_eq!(parse(q! { { d } }).unwrap(), MyEnum::D(true)); ::std::assert_eq!( parse(q! { { e("hello", 4.0) } }).unwrap(), MyEnum::E("hello".into(), 4.0), ); ::std::assert_eq!(parse(q! { { f } }).unwrap(), MyEnum::F {}); ::std::assert_eq!(parse(q! { { f() } }).unwrap(), MyEnum::F {}); ::std::assert_eq!(parse(q! { { f = {} } }).unwrap(), MyEnum::F {}); ::std::assert_eq!( parse(q! { { g(themod::theitem) } }).unwrap(), MyEnum::G { pass: ::syn::parse_quote! { themod::theitem } } ); ::std::assert_eq!( parse(q! { { g = themod::theitem } }).unwrap(), MyEnum::G { pass: ::syn::parse_quote! { themod::theitem } } ); ::std::assert_eq!( parse(q! { { h(s = "qwerty", f = 1.0) } }).unwrap(), MyEnum::H { s: "qwerty".into(), f: 1.0 } ); ::std::assert_eq!( parse(q! { { j_a = 123, j_b = "asdf" } }).unwrap(), MyEnum::FlatJ { named: MyFlatNamed { j_a: 123, j_b: "asdf".into(), } }, ); ::std::assert_eq!( parse(q! { { i = "asdf" } }).unwrap(), MyEnum::FlatI { i: "asdf".into() } ); ::std::assert_eq!( parse(q! { { x() } }).unwrap_err_string(), "unknown field `x`, expected one of `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, fields from `FlatJ`", ); ::std::assert_eq!( parse(q! { { k } }).unwrap_err_string(), "unknown field `k`, expected one of `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, fields from `FlatJ`", ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum MySimpleEnum { A, B, C, } #[test] fn parse_simple_enum() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { { a } }).unwrap(), MySimpleEnum::A); ::std::assert_eq!(parse(q! { { b } }).unwrap(), MySimpleEnum::B); ::std::assert_eq!(parse(q! { { c } }).unwrap(), MySimpleEnum::C); ::std::assert_eq!( parse(q! { { a, b } }).unwrap_err_string(), "expected only one enum variant, got `a` and `b`" ); ::std::assert_eq!( parse(q! { { a, c } }).unwrap_err_string(), "expected only one enum variant, got `a` and `c`" ); ::std::assert_eq!( parse(q! { { d } }).unwrap_err_string(), "unknown field `d`, expected one of `a`, `b`, `c`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct StructWith { normal: ::std::string::String, #[deluxe(with = ::deluxe::with::from_str)] str_int: i32, } ::deluxe::define_with_optional!( pub mod custom_int_option, ::deluxe::with::from_str, i32, ); ::deluxe::define_with_collection!( pub mod custom_int_vec, ::deluxe::with::from_str, ::std::vec::Vec, ); ::deluxe::define_with_map!( pub mod custom_int_map, ::deluxe::with::mod_path, ::deluxe::with::from_str, ::std::collections::HashMap<::syn::Path, i32>, ); #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] #[deluxe(transparent(flatten_unnamed, append))] struct StructWithTransparent { #[deluxe(with = custom_int_vec)] int_vec: ::std::vec::Vec, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct StructWithExtended { #[deluxe(with = custom_int_option)] int: ::std::option::Option, #[deluxe(with = custom_int_vec)] int_vec: ::std::vec::Vec, #[deluxe(append, rename = int_append, with = custom_int_vec)] int_vec2: ::std::vec::Vec, #[deluxe(append, default)] int_vec3: StructWithTransparent, #[deluxe(rest, with = custom_int_map)] int_map: ::std::collections::HashMap<::syn::Path, i32>, } #[test] fn parse_with() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { normal = "abc", str_int = "123" } }).unwrap(), StructWith { normal: "abc".into(), str_int: 123 } ); ::std::assert_eq!( parse(q! { { normal = "abc", str_int = 123 } }).unwrap_err_string(), "expected string literal" ); let make_path = |s| ::syn::parse_str::<::syn::Path>(s).unwrap(); let parse = parse_meta::; ::std::assert_eq!( parse(q! { { int = -4, int_vec = ["1", "2"] } }).unwrap_err_string(), "expected string literal" ); ::std::assert_eq!( parse(q! { { int_vec = [1] } }).unwrap_err_string(), "expected string literal" ); ::std::assert_eq!( parse(q! { { int = "-4", int_vec = ["1", "2"] } }).unwrap(), StructWithExtended { int: Some(-4), int_vec: ::std::vec![1, 2], int_vec2: ::std::vec![], int_vec3: Default::default(), int_map: [].into() } ); ::std::assert_eq!( parse(q! { { int_vec = [], int_append = "1", int_append = "2" } }).unwrap(), StructWithExtended { int: None, int_vec: ::std::vec![], int_vec2: ::std::vec![1, 2], int_vec3: Default::default(), int_map: [].into() } ); ::std::assert_eq!( parse(q! { { int_vec = [], int_append = "1", unknown = "2", hello = "3" } }).unwrap(), StructWithExtended { int: None, int_vec: ::std::vec![], int_vec2: ::std::vec![1], int_vec3: Default::default(), int_map: [(make_path("unknown"), 2), (make_path("hello"), 3)].into() } ); ::std::assert_eq!( parse(q! { { int_vec = [], int_vec3 = "1", int_vec3 = "2" } }).unwrap(), StructWithExtended { int: None, int_vec: ::std::vec![], int_vec2: ::std::vec![], int_vec3: StructWithTransparent { int_vec: ::std::vec![1, 2], }, int_map: [].into() } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct StructNames { #[deluxe(rename = sixty_four, default)] renamed: u64, #[deluxe(alias = thirty_two, default)] aliased: u32, #[deluxe(alias = another, alias = another2, default)] many_aliases: u32, #[deluxe(rename = sixteen, alias = another_sixteen, alias = another2_sixteen, default)] alias_renamed: u16, } #[test] fn struct_field_names() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { { sixty_four = 64 } }).unwrap().renamed, 64); ::std::assert_eq!( parse(q! { { renamed = 64 } }).unwrap_err_string(), "unknown field `renamed`" ); ::std::assert_eq!( parse(q! { { sixty_four = 64, sixty_four = 65 } }).unwrap_err_string(), "duplicate attribute for `sixty_four`" ); ::std::assert_eq!( parse(q! { { sixty_four = 64, renamed = 65 } }).unwrap_err_string(), "unknown field `renamed`" ); ::std::assert_eq!(parse(q! { { aliased = 32 } }).unwrap().aliased, 32); ::std::assert_eq!(parse(q! { { thirty_two = 32 } }).unwrap().aliased, 32); ::std::assert_eq!( parse(q! { { aliased = 32, thirty_two = 33 } }).unwrap_err_string(), "duplicate attribute for `aliased`" ); ::std::assert_eq!( parse(q! { { many_aliases = 32 } }).unwrap().many_aliases, 32 ); ::std::assert_eq!(parse(q! { { another = 32 } }).unwrap().many_aliases, 32); ::std::assert_eq!(parse(q! { { another2 = 32 } }).unwrap().many_aliases, 32); ::std::assert_eq!( parse(q! { { many_aliases = 32, another = 33, another2 = 34 } }).unwrap_err_string(), "duplicate attribute for `many_aliases`, duplicate attribute for `many_aliases`" ); ::std::assert_eq!(parse(q! { { sixteen = 16 } }).unwrap().alias_renamed, 16); ::std::assert_eq!( parse(q! { { another_sixteen = 16 } }) .unwrap() .alias_renamed, 16 ); ::std::assert_eq!( parse(q! { { another2_sixteen = 16 } }) .unwrap() .alias_renamed, 16 ); ::std::assert_eq!( parse(q! { { alias_renamed = 16 } }).unwrap_err_string(), "unknown field `alias_renamed`, did you mean `aliased`?" ); ::std::assert_eq!( ::field_names(), &[ "sixty_four", "aliased", "thirty_two", "many_aliases", "another", "another2", "sixteen", "another_sixteen", "another2_sixteen" ] ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum EnumNames { #[deluxe(rename = renamed_a)] A, #[deluxe(alias = alias_b)] B, #[deluxe(alias = another_c, alias = another2_c)] C, #[deluxe(rename = renamed_d, alias = another_d, alias = another2_d)] D, } #[test] fn enum_field_names() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { { renamed_a } }).unwrap(), EnumNames::A); ::std::assert_eq!(parse(q! { { b } }).unwrap(), EnumNames::B); ::std::assert_eq!(parse(q! { { alias_b } }).unwrap(), EnumNames::B); ::std::assert_eq!(parse(q! { { c } }).unwrap(), EnumNames::C); ::std::assert_eq!(parse(q! { { another_c } }).unwrap(), EnumNames::C); ::std::assert_eq!(parse(q! { { another2_c } }).unwrap(), EnumNames::C); ::std::assert_eq!(parse(q! { { renamed_d } }).unwrap(), EnumNames::D); ::std::assert_eq!(parse(q! { { another_d } }).unwrap(), EnumNames::D); ::std::assert_eq!(parse(q! { { another2_d } }).unwrap(), EnumNames::D); ::std::assert_eq!( parse(q! { { a } }).unwrap_err_string(), "unknown field `a`, expected one of `renamed_a`, `b`, `c`, `renamed_d`" ); ::std::assert_eq!( parse(q! { { d } }).unwrap_err_string(), "unknown field `d`, expected one of `renamed_a`, `b`, `c`, `renamed_d`" ); ::std::assert_eq!( ::field_names(), &[ "renamed_a", "b", "alias_b", "c", "another_c", "another2_c", "renamed_d", "another_d", "another2_d", ] ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] #[deluxe(default)] struct StructDefault { value0: i32, #[deluxe(default = 1)] value1: i32, } #[test] fn struct_defaults() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { } }).unwrap(), StructDefault { value0: 0, value1: 1 } ); ::std::assert_eq!( parse(q! { { value0 = -1, value1 = 2 } }).unwrap(), StructDefault { value0: -1, value1: 2 } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(default = Self { value1: 1, value2: 2 })] struct StructDefaultExpr { value1: i32, value2: i32, } #[test] fn struct_default_expr() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { } }).unwrap(), StructDefaultExpr { value1: 1, value2: 2 } ); ::std::assert_eq!( parse(q! { { value1 = 11 } }).unwrap(), StructDefaultExpr { value1: 11, value2: 2 } ); ::std::assert_eq!( parse(q! { { value2 = 22 } }).unwrap(), StructDefaultExpr { value1: 1, value2: 22 } ); ::std::assert_eq!( parse(q! { { value1 = 11, value2 = 22 } }).unwrap(), StructDefaultExpr { value1: 11, value2: 22 } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] struct StructDefaultTuple(i32, #[deluxe(default)] i32); #[test] fn struct_default_tuple() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! {}).unwrap_err_string(), "unexpected end of input, expected parentheses" ); ::std::assert_eq!( parse(q! { () }).unwrap_err_string(), "missing required field 0" ); ::std::assert_eq!(parse(q! { (1) }).unwrap(), StructDefaultTuple(1, 0)); ::std::assert_eq!(parse(q! { (1, 2) }).unwrap(), StructDefaultTuple(1, 2)); ::std::assert_eq!( parse(q! { (1, 2, 3) }).unwrap_err_string(), "unexpected token `3`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(default = Self(1, 2))] struct StructDefaultTupleExpr(i32, i32); #[test] fn struct_default_tuple_expr() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { () }).unwrap(), StructDefaultTupleExpr(1, 2)); ::std::assert_eq!(parse(q! { (3) }).unwrap(), StructDefaultTupleExpr(3, 2)); ::std::assert_eq!(parse(q! { (3,) }).unwrap(), StructDefaultTupleExpr(3, 2)); ::std::assert_eq!(parse(q! { (3, 4) }).unwrap(), StructDefaultTupleExpr(3, 4)); ::std::assert_eq!(parse(q! { (3, 4,) }).unwrap(), StructDefaultTupleExpr(3, 4)); ::std::assert_eq!( parse(q! { (3, 4,,) }).unwrap_err_string(), "unexpected token `,`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct FieldDefaults { #[deluxe(default = MyNewtype(::std::string::String::new()))] name: MyNewtype, #[deluxe(default)] value0: i32, #[deluxe(default = 1)] value1: i32, value: i32, } #[test] fn field_defaults() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { } }).unwrap_err_string(), "missing required field `value`" ); ::std::assert_eq!( parse(q! { { value = 123 } }).unwrap(), FieldDefaults { name: MyNewtype(String::from("")), value0: 0, value1: 1, value: 123, } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] #[deluxe(default)] enum EnumDefault { #[default] A, B, C(#[deluxe(default)] i32), } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(default = Self::A)] enum EnumDefaultExpr { A, B, C, } #[test] fn enum_defaults() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!(parse(q! { { } }).unwrap(), EnumDefault::A); ::std::assert_eq!(parse(q! { { c } }).unwrap(), EnumDefault::C(0)); ::std::assert_eq!(parse(q! { { c() } }).unwrap(), EnumDefault::C(0)); ::std::assert_eq!(parse(q! { { c = () } }).unwrap(), EnumDefault::C(0)); ::std::assert_eq!(parse(q! { { c(1) } }).unwrap(), EnumDefault::C(1)); ::std::assert_eq!(parse(q! { { c(1,) } }).unwrap(), EnumDefault::C(1)); ::std::assert_eq!( parse(q! { { c = (,) } }).unwrap_err_string(), "expected integer literal" ); let parse = parse_meta::; ::std::assert_eq!(parse(q! { { } }).unwrap(), EnumDefaultExpr::A); } use ::deluxe as renamed_deluxe; #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(crate = renamed_deluxe)] struct RenamedCrate(i32); #[test] fn renamed_crate() { let parse = parse_meta::; ::std::assert_eq!(parse(q! { (50) }).unwrap(), RenamedCrate(50)); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(allow_unknown_fields)] struct StructAllowUnknown { value: i32, } #[test] fn struct_allow_unknown() { let parse = parse_meta::; ::std::assert_eq!( parse(q! { { value = 10 } }).unwrap(), StructAllowUnknown { value: 10 } ); ::std::assert_eq!( parse(q! { { value = 10, another = "hello" } }).unwrap(), StructAllowUnknown { value: 10 } ); ::std::assert_eq!( parse( q! { { value = 10, complex = ::c::X + 123 + (Z(Y) % { x[0].a }), another = "hello" } } ) .unwrap(), StructAllowUnknown { value: 10 } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum EnumAllow { Known { value: i32, }, #[deluxe(allow_unknown_fields)] Unknown { value: i32, }, FlattenedKnown { #[deluxe(flatten)] s: MyNamed, }, FlattenedUnknown { #[deluxe(flatten)] s: StructAllowUnknown, }, } #[test] fn enum_allow_unknown() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { known(value(50)) } }).unwrap(), EnumAllow::Known { value: 50 } ); ::std::assert_eq!( parse(q! { { known(value(50)), unknown(value(51)) } }).unwrap_err_string(), "expected only one enum variant, got `known` and `unknown`" ); ::std::assert_eq!( parse(q! { { known(value(50), another("thing")) } }).unwrap_err_string(), "unknown field `another`" ); ::std::assert_eq!( parse(q! { { known(value(50), another("thing")), unknown(value("50")) } }).unwrap_err_string(), "unknown field `another`, expected only one enum variant, got `known` and `unknown`, expected integer literal" ); ::std::assert_eq!( parse(q! { { unknown(value(50)) } }).unwrap(), EnumAllow::Unknown { value: 50 } ); ::std::assert_eq!( parse(q! { { unknown(value(50), another("thing")) } }).unwrap(), EnumAllow::Unknown { value: 50 } ); ::std::assert_eq!( parse(q! { { flattened_known(a(50), b("thing")) } }).unwrap(), EnumAllow::FlattenedKnown { s: MyNamed { a: 50, b: String::from("thing") } } ); ::std::assert_eq!( parse(q! { { flattened_known(a(50), b("thing"), another("two")) } }).unwrap_err_string(), "unknown field `another`" ); ::std::assert_eq!( parse(q! { { flattened_unknown(value(60)) } }).unwrap(), EnumAllow::FlattenedUnknown { s: StructAllowUnknown { value: 60 } } ); ::std::assert_eq!( parse(q! { { flattened_unknown(value(60), another("thing")) } }).unwrap(), EnumAllow::FlattenedUnknown { s: StructAllowUnknown { value: 60 } } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(flatten_named))] struct MyTransparentUnnamedStruct(MyNamed); #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(flatten_named))] struct MyTransparentNamedStruct { named: MyNamed, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(flatten_unnamed, append))] struct MyTransparentUnnamedVec(::std::vec::Vec); #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(flatten_unnamed, append))] struct MyTransparentNamedVec { nums: ::std::vec::Vec, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(rest))] struct MyTransparentUnnamedMap(::std::collections::HashMap<::syn::Path, i32>); #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(transparent(rest))] struct MyTransparentNamedMap { nums: ::std::collections::HashMap<::syn::Path, i32>, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] enum TransparentHolder { A { #[deluxe(flatten)] s: MyTransparentUnnamedStruct, }, B { #[deluxe(flatten)] s: MyTransparentNamedStruct, }, C(#[deluxe(flatten)] MyTransparentUnnamedVec), D(#[deluxe(flatten)] MyTransparentNamedVec), E { #[deluxe(append)] v: MyTransparentUnnamedVec, }, F { #[deluxe(append)] v: MyTransparentNamedVec, }, G { #[deluxe(rest)] r: MyTransparentUnnamedMap, }, H { #[deluxe(rest)] r: MyTransparentNamedMap, }, } #[test] fn transparent_flat() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { a(a(4), b("hello")) } }).unwrap(), TransparentHolder::A { s: MyTransparentUnnamedStruct(MyNamed { a: 4, b: String::from("hello") }) } ); ::std::assert_eq!( parse(q! { { b(a(4), b("hello")) } }).unwrap(), TransparentHolder::B { s: MyTransparentNamedStruct { named: MyNamed { a: 4, b: String::from("hello") } } } ); ::std::assert_eq!( parse(q! { { c } }).unwrap(), TransparentHolder::C(MyTransparentUnnamedVec(::std::vec![])) ); ::std::assert_eq!( parse(q! { { c() } }).unwrap(), TransparentHolder::C(MyTransparentUnnamedVec(::std::vec![])) ); ::std::assert_eq!( parse(q! { { c(1, 2, 3) } }).unwrap(), TransparentHolder::C(MyTransparentUnnamedVec(::std::vec![1, 2, 3])) ); ::std::assert_eq!( parse(q! { { d } }).unwrap(), TransparentHolder::D(MyTransparentNamedVec { nums: ::std::vec![] }) ); ::std::assert_eq!( parse(q! { { d() } }).unwrap(), TransparentHolder::D(MyTransparentNamedVec { nums: ::std::vec![] }) ); ::std::assert_eq!( parse(q! { { d(1, 2, 3) } }).unwrap(), TransparentHolder::D(MyTransparentNamedVec { nums: ::std::vec![1, 2, 3] }) ); ::std::assert_eq!( parse(q! { { e(v(1), v(2), v(3)) } }).unwrap(), TransparentHolder::E { v: MyTransparentUnnamedVec(::std::vec![1, 2, 3]) } ); ::std::assert_eq!( parse(q! { { f(v(1), v(2), v(3)) } }).unwrap(), TransparentHolder::F { v: MyTransparentNamedVec { nums: ::std::vec![1, 2, 3] } } ); let map = [("a", 1), ("b", 2), ("c", 3)] .into_iter() .map(|(k, v)| { let k = ::syn::Ident::new(k, ::proc_macro2::Span::call_site()); let k: ::syn::Path = ::syn::parse_quote! { #k }; (k, v) }) .collect::<::std::collections::HashMap<_, _>>(); ::std::assert_eq!( parse(q! { { g(a(1), b(2), c(3)) } }).unwrap(), TransparentHolder::G { r: MyTransparentUnnamedMap(map.clone()) } ); ::std::assert_eq!( parse(q! { { h(a(1), b(2), c(3)) } }).unwrap(), TransparentHolder::H { r: MyTransparentNamedMap { nums: map } } ); } #[derive(PartialEq, Debug)] struct CustomAppendSum(i32); impl ::deluxe::ParseMetaAppend for CustomAppendSum { fn parse_meta_append<'s, S, I, P>(inputs: &[S], paths: I) -> ::deluxe::Result where S: ::std::borrow::Borrow>, I: ::std::iter::IntoIterator, I::IntoIter: ::std::clone::Clone, P: ::std::convert::AsRef, { use ::std::prelude::v1::*; let mut value = 0; let errors = ::deluxe::Errors::new(); let paths = paths.into_iter(); ::deluxe_core::parse_helpers::parse_struct(inputs, |input, p, pspan| { if paths.clone().any(|path| path.as_ref() == p) { value += ::deluxe_core::parse_helpers::parse_named_meta_item::(input, pspan)?; } else { ::deluxe_core::parse_helpers::skip_meta_item(input); } ::deluxe::Result::Ok(()) })?; errors.check()?; ::deluxe::Result::Ok(Self(value)) } } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct CustomAppend { first: i32, #[deluxe(append)] sum: CustomAppendSum, } #[test] fn custom_append_sum() { let parse = parse_meta::; ::std::assert_eq!( parse(q! { { first = 50, sum = 2, sum = 3 } }).unwrap(), CustomAppend { first: 50, sum: CustomAppendSum(5) } ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct MyOptionalNamed { #[deluxe(default)] a: i32, #[deluxe(default)] b: ::std::string::String, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct PositionalAndNamed( #[deluxe(default)] i32, #[deluxe(default)] i32, #[deluxe(flatten)] MyOptionalNamed, ); #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct NestedPositionalAndNamed( i32, #[deluxe(flatten)] MyUnnamed, #[deluxe(default)] i32, #[deluxe(flatten)] PositionalAndNamed, ); #[test] fn positional_and_named() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { (1) }).unwrap(), PositionalAndNamed(1, 0, MyOptionalNamed { a: 0, b: "".into() }) ); ::std::assert_eq!( parse(q! { (1, 2) }).unwrap(), PositionalAndNamed(1, 2, MyOptionalNamed { a: 0, b: "".into() }) ); ::std::assert_eq!( parse(q! { (1, 2, b = "4" ) }).unwrap(), PositionalAndNamed( 1, 2, MyOptionalNamed { a: 0, b: "4".into() } ) ); ::std::assert_eq!( parse(q! { (1, 2, a = 3, b = "4" ) }).unwrap(), PositionalAndNamed( 1, 2, MyOptionalNamed { a: 3, b: "4".into() } ) ); ::std::assert_eq!( parse(q! { (1, 2, b = "4", a = 3 ) }).unwrap(), PositionalAndNamed( 1, 2, MyOptionalNamed { a: 3, b: "4".into() } ) ); let parse = parse_meta::; ::std::assert_eq!( parse(q! { (1, 2, "3") }).unwrap(), NestedPositionalAndNamed( 1, MyUnnamed(2, "3".into()), 0, PositionalAndNamed(0, 0, MyOptionalNamed { a: 0, b: "".into() }) ) ); ::std::assert_eq!( parse(q! { (1, 2, "3", 4, 5) }).unwrap(), NestedPositionalAndNamed( 1, MyUnnamed(2, "3".into()), 4, PositionalAndNamed(5, 0, MyOptionalNamed { a: 0, b: "".into() }) ) ); ::std::assert_eq!( parse(q! { (1, 2, "3", 4, 5, 6, a = 7, b = "8" ) }).unwrap(), NestedPositionalAndNamed( 1, MyUnnamed(2, "3".into()), 4, PositionalAndNamed( 5, 6, MyOptionalNamed { a: 7, b: "8".into() } ) ) ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] enum KwEnum { #[default] A, B, Const, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct FlattenedEnum { #[deluxe(flatten)] kw: KwEnum, } #[test] fn flattened_enum() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { a } }).unwrap(), FlattenedEnum { kw: KwEnum::A } ); ::std::assert_eq!( parse(q! { { b } }).unwrap(), FlattenedEnum { kw: KwEnum::B } ); ::std::assert_eq!( parse(q! { { const } }).unwrap(), FlattenedEnum { kw: KwEnum::Const } ); ::std::assert_eq!( parse(q! { {} }).unwrap_err_string(), "expected one of `a`, `b`, `const`" ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct FlagStruct { myflag: ::deluxe::Flag, #[deluxe(default)] value: i32, } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] // should always error when encountering the field struct FlagTupleStruct(::deluxe::Flag); #[test] fn flag() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { myflag } }).unwrap(), FlagStruct { myflag: true.into(), value: 0, } ); ::std::assert_eq!( parse(q! { {} }).unwrap(), FlagStruct { myflag: false.into(), value: 0, } ); ::std::assert_eq!( parse(q! { { myflag, value = 123 } }).unwrap(), FlagStruct { myflag: true.into(), value: 123, } ); ::std::assert_eq!( parse(q! { { myflag = true } }).unwrap_err_string(), "unexpected token", ); ::std::assert_eq!( parse(q! { { myflag(true) } }).unwrap_err_string(), "unexpected token", ); let parse = parse_meta::; ::std::assert_eq!( parse(q! { (myflag) }).unwrap_err_string(), "field with type `Flag` can only be a named field with no value", ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(and_then = Self::validate_min, and_then = Self::validate_max)] struct AndThens { a: ::deluxe::SpannedValue, b: i32, } impl AndThens { fn validate_min(self) -> ::deluxe::Result { if *self.a + self.b <= -10 { ::deluxe::Result::Err(::deluxe::Error::new( ::syn::spanned::Spanned::span(&self.a), "sum of a and b must be above -10", )) } else { ::deluxe::Result::Ok(self) } } fn validate_max(self) -> ::deluxe::Result { if *self.a + self.b >= 10 { ::deluxe::Result::Err(::deluxe::Error::new( ::syn::spanned::Spanned::span(&self.a), "sum of a and b must be below 10", )) } else { ::deluxe::Result::Ok(self) } } } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] #[deluxe(and_then = Self::validate_min, and_then = Self::validate_max)] enum AndThensEnum { Values { a: ::deluxe::SpannedValue, b: i32, }, Empty, } impl AndThensEnum { fn validate_min(self) -> ::deluxe::Result { if let Self::Values { a, b } = &self { if **a + *b <= -10 { return ::deluxe::Result::Err(::deluxe::Error::new( ::syn::spanned::Spanned::span(a), "sum of a and b must be above -10", )); } } ::deluxe::Result::Ok(self) } fn validate_max(self) -> ::deluxe::Result { if let Self::Values { a, b } = &self { if **a + *b >= 10 { return ::deluxe::Result::Err(::deluxe::Error::new( ::syn::spanned::Spanned::span(a), "sum of a and b must be below 10", )); } } ::deluxe::Result::Ok(self) } } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] #[deluxe(and_then = Self::validate)] struct OnlyOne { a: ::std::option::Option<::std::string::String>, b: ::std::option::Option<::std::string::String>, } impl OnlyOne { fn validate(self) -> ::deluxe::Result { let errors = ::deluxe::Errors::new(); let Self { a, b } = &self; ::deluxe::validations::only_one!("", &errors, a, b); errors.into_result(self) } } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, Default, )] #[deluxe(and_then = Self::validate)] struct AllOrNone { a: ::std::option::Option<::std::string::String>, b: ::std::option::Option<::std::string::String>, } impl AllOrNone { fn validate(self) -> ::deluxe::Result { let errors = ::deluxe::Errors::new(); let Self { a, b } = &self; ::deluxe::validations::all_or_none!("", &errors, a, b); errors.into_result(self) } } #[test] fn and_then() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { a = 5, b = 4 } }).unwrap(), AndThens { a: 5.into(), b: 4 } ); ::std::assert_eq!( parse(q! { { a = -5, b = -6 } }).unwrap_err_string(), "sum of a and b must be above -10", ); ::std::assert_eq!( parse(q! { { a = 5, b = 6 } }).unwrap_err_string(), "sum of a and b must be below 10", ); let parse = parse_meta::; ::std::assert_eq!(parse(q! { { empty } }).unwrap(), AndThensEnum::Empty); ::std::assert_eq!( parse(q! { { values(a = 5, b = 4) } }).unwrap(), AndThensEnum::Values { a: 5.into(), b: 4 } ); ::std::assert_eq!( parse(q! { { values(a = -5, b = -6) } }).unwrap_err_string(), "sum of a and b must be above -10", ); ::std::assert_eq!( parse(q! { { values(a = 5, b = 6) } }).unwrap_err_string(), "sum of a and b must be below 10", ); let parse = parse_meta::; ::std::assert_eq!(parse(q! { {} }).unwrap(), OnlyOne::default()); ::std::assert_eq!( parse(q! { {a("a")} }).unwrap(), OnlyOne { a: Some("a".into()), b: None } ); ::std::assert_eq!( parse(q! { {b("b")} }).unwrap(), OnlyOne { a: None, b: Some("b".into()), } ); // error appears twice, once on each attribute ::std::assert_eq!( parse(q! { {a("a"), b("b")} }).unwrap_err_string(), "only one of `a`, `b` is allowed, only one of `a`, `b` is allowed", ); let parse = parse_meta::; ::std::assert_eq!(parse(q! { {} }).unwrap(), AllOrNone::default()); ::std::assert_eq!( parse(q! { {a("a"), b("b")} }).unwrap(), AllOrNone { a: Some("a".into()), b: Some("b".into()), } ); ::std::assert_eq!( parse(q! { {a("a")} }).unwrap_err_string(), "`b` must also be set in order to use `a`", ); ::std::assert_eq!( parse(q! { {b("b")} }).unwrap_err_string(), "`a` must also be set in order to use `b`", ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct FieldTransforms { #[deluxe(map = |x: ::syn::Ident| ::std::string::ToString::to_string(&x))] ident: ::std::string::String, #[deluxe(map = |x: ::syn::Ident| ::std::string::ToString::to_string(&x))] #[deluxe(map = |s| ::std::format!("prefix_{s}"))] prefixed_ident: ::std::string::String, #[deluxe(and_then = |u: u32| >::try_from(u) .map_err(|_| ::syn::Error::new(::proc_macro2::Span::call_site(), "my_int too big")))] my_int: u16, #[deluxe(and_then = |u: u32| >::try_from(u) .map_err(|_| ::syn::Error::new(::proc_macro2::Span::call_site(), "is_one too big")))] #[deluxe(map = |u| u == 1)] is_one: bool, } #[test] fn field_transforms() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { ident = hello, prefixed_ident = world, my_int = 200, is_one = 1, } }).unwrap(), FieldTransforms { ident: String::from("hello"), prefixed_ident: String::from("prefix_world"), my_int: 200, is_one: true } ); ::std::assert_eq!( parse(q! { { ident = goodbye, prefixed_ident = moon, my_int = 300, is_one = 123, } }) .unwrap(), FieldTransforms { ident: String::from("goodbye"), prefixed_ident: String::from("prefix_moon"), my_int: 300, is_one: false } ); ::std::assert_eq!( parse(q! { { ident = hello, prefixed_ident = world, my_int = 100000, is_one = 1, } }) .unwrap_err_string(), "my_int too big", ); ::std::assert_eq!( parse(q! { { ident = hello, prefixed_ident = world, my_int = 200000, is_one = 100000, } }) .unwrap_err_string(), "my_int too big, is_one too big", ); } #[derive( ::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem, PartialEq, Debug, )] struct RawIdentKeys { r#struct: ::syn::Type, r#trait: ::syn::Type, } #[test] fn raw_ident_keys() { use ::std::prelude::v1::*; let parse = parse_meta::; ::std::assert_eq!( parse(q! { { struct = A, trait = B } }).unwrap(), RawIdentKeys { r#struct: ::syn::parse_quote! { A }, r#trait: ::syn::parse_quote! { B }, } ); } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem)] struct NoDebugInner { _a: i32, _b: ::std::string::String, } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem)] struct NoDebug { _a: i32, _b: ::std::string::String, _c: NoDebugInner, } #[derive(::deluxe::ParseAttributes, ::deluxe::ExtractAttributes, ::deluxe::ParseMetaItem)] enum NoDebugEnum { _A(NoDebug), _B(NoDebugInner), } deluxe-0.5.0/tests/test_util/mod.rs000064400000000000000000000017711046102023000154250ustar 00000000000000#![allow(dead_code)] use ::proc_macro2::TokenStream; use ::std::prelude::v1::*; pub trait SynResultExt { fn unwrap_err_string(self) -> String; } impl SynResultExt for ::syn::Result { fn unwrap_err_string(self) -> String { self.unwrap_err() .into_iter() .map(|e| e.to_string()) .collect::>() .join(", ") } } #[inline] pub fn parse_meta(s: TokenStream) -> ::deluxe::Result { use ::syn::parse::Parser; let parser = |stream: ::syn::parse::ParseStream<'_>| { ::parse_meta_item(stream, ::deluxe::ParseMode::Unnamed) }; parser.parse2(s) } #[inline] pub fn parse_flag() -> ::deluxe::Result { use ::syn::parse::Parser; let parser = |stream: ::syn::parse::ParseStream<'_>| { ::parse_meta_item_flag(stream.span()) }; parser.parse2(Default::default()) }