arg_enum_proc_macro-0.3.4/.cargo_vcs_info.json0000644000000001360000000000100150410ustar { "git": { "sha1": "28b02f0ef1eb548e1e75bd24effde08d64be3101" }, "path_in_vcs": "" }arg_enum_proc_macro-0.3.4/.gitignore000064400000000000000000000000351046102023000156170ustar 00000000000000/target **/*.rs.bk Cargo.lockarg_enum_proc_macro-0.3.4/Cargo.toml0000644000000020070000000000100130360ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "arg_enum_proc_macro" version = "0.3.4" authors = ["Luca Barbato "] description = "A procedural macro compatible with clap arg_enum" readme = "README.md" keywords = [ "proc_macro", "arg_enum", ] license = "MIT" repository = "https://github.com/lu-zero/arg_enum_proc_macro" [lib] test = false proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" features = ["extra-traits"] [dev-dependencies.trybuild] version = "1.0" arg_enum_proc_macro-0.3.4/Cargo.toml.orig000064400000000000000000000007711046102023000165250ustar 00000000000000[package] name = "arg_enum_proc_macro" version = "0.3.4" authors = ["Luca Barbato "] description = "A procedural macro compatible with clap arg_enum" repository = "https://github.com/lu-zero/arg_enum_proc_macro" readme = "README.md" keywords = ["proc_macro", "arg_enum"] license = "MIT" edition = "2018" [lib] proc-macro = true test = false [dependencies] syn = { version = "2.0", features = ["extra-traits"] } quote = "1.0" proc-macro2 = "1.0" [dev-dependencies] trybuild = "1.0" arg_enum_proc_macro-0.3.4/LICENSE000064400000000000000000000020551046102023000146400ustar 00000000000000MIT License Copyright (c) 2018 Luca Barbato 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. arg_enum_proc_macro-0.3.4/README.md000064400000000000000000000020441046102023000151100ustar 00000000000000# Procedural macro derive that mimics `arg_enum!` from [clap](https://clap.rs) ![Crates.io](https://img.shields.io/crates/v/arg_enum_proc_macro) ![docs.rs](https://docs.rs/mio/badge.svg) [![dependency status](https://deps.rs/repo/github/lu-zero/arg_enum_proc_macro/status.svg)](https://deps.rs/repo/github/lu-zero/arg_enum_proc_macro) ## Usage In `Cargo.toml`: ``` toml [dependencies] arg_enum_proc_macro = "0.3" ``` In the rust code: ``` rust use arg_enum_proc_macro::ArgEnum; /// All the possible states of Foo #[derive(ArgEnum)] pub enum Foo { /// Initial state Unk, /// Foo is on On, /// Foo is off Off, } ``` ### Aliases It is possible to express an alias using the attribute `arg_enum(alias = "AliasVariant")`. The `FromStr` will map the "AliasVariant" string to the decorated enum variant: ``` rust /// All the possible states of Foo #[derive(ArgEnum)] pub enum Foo { /// Initial state Unk, /// Foo is on #[arg_enum(alias = "Up")] On, /// Foo is off #[arg_enum(alias = "Down")] Off, } ``` arg_enum_proc_macro-0.3.4/src/lib.rs000064400000000000000000000221771046102023000155450ustar 00000000000000//! # arg_enum_proc_macro //! //! This crate consists in a procedural macro derive that provides the //! same implementations that clap the [`clap::arg_enum`][1] macro provides: //! [`std::fmt::Display`], [`std::str::FromStr`] and a `variants()` function. //! //! By using a procedural macro it allows documenting the enum fields //! correctly and avoids the requirement of expanding the macro to use //! the structure with [cbindgen](https://crates.io/crates/cbindgen). //! //! [1]: https://docs.rs/clap/2.32.0/clap/macro.arg_enum.html //! #![recursion_limit = "128"] extern crate proc_macro; use proc_macro2::{Literal, Punct, Span, TokenStream, TokenTree}; use quote::{quote, quote_spanned}; use std::iter::FromIterator; use syn::Lit::{self}; use syn::Meta::{self}; use syn::{parse_macro_input, Data, DeriveInput, Expr, ExprLit, Ident, LitStr}; /// Implement [`std::fmt::Display`], [`std::str::FromStr`] and `variants()`. /// /// The invocation: /// ``` no_run /// use arg_enum_proc_macro::ArgEnum; /// /// #[derive(ArgEnum)] /// enum Foo { /// A, /// /// Describe B /// #[arg_enum(alias = "Bar")] /// B, /// /// Describe C /// /// Multiline /// #[arg_enum(name = "Baz")] /// C, /// } /// ``` /// /// produces: /// ``` no_run /// enum Foo { /// A, /// B, /// C /// } /// impl ::std::str::FromStr for Foo { /// type Err = String; /// /// fn from_str(s: &str) -> ::std::result::Result { /// match s { /// "A" | _ if s.eq_ignore_ascii_case("A") => Ok(Foo::A), /// "B" | _ if s.eq_ignore_ascii_case("B") => Ok(Foo::B), /// "Bar" | _ if s.eq_ignore_ascii_case("Bar") => Ok(Foo::B), /// "Baz" | _ if s.eq_ignore_ascii_case("Baz") => Ok(Foo::C), /// _ => Err({ /// let v = vec![ "A", "B", "Bar", "Baz" ]; /// format!("valid values: {}", v.join(" ,")) /// }), /// } /// } /// } /// impl ::std::fmt::Display for Foo { /// fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { /// match *self { /// Foo::A => write!(f, "A"), /// Foo::B => write!(f, "B"), /// Foo::C => write!(f, "C"), /// } /// } /// } /// /// impl Foo { /// /// Returns an array of valid values which can be converted into this enum. /// #[allow(dead_code)] /// pub fn variants() -> [&'static str; 4] { /// [ "A", "B", "Bar", "Baz", ] /// } /// #[allow(dead_code)] /// pub fn descriptions() -> [(&'static [&'static str], &'static [&'static str]) ;3] { /// [(&["A"], &[]), /// (&["B", "Bar"], &[" Describe B"]), /// (&["Baz"], &[" Describe C", " Multiline"]),] /// } /// } /// ``` #[proc_macro_derive(ArgEnum, attributes(arg_enum))] pub fn arg_enum(items: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(items as DeriveInput); let name = input.ident; let variants = if let Data::Enum(data) = input.data { data.variants } else { panic!("Only enum supported"); }; let all_variants: Vec<(TokenTree, &Ident)> = variants .iter() .flat_map(|item| { let id = &item.ident; if !item.fields.is_empty() { panic!( "Only enum with unit variants are supported! \n\ Variant {}::{} is not an unit variant", name, &id.to_string() ); } let lit: TokenTree = Literal::string(&id.to_string()).into(); let mut all_lits = vec![(lit, id)]; item.attrs .iter() .filter(|attr| attr.path().is_ident("arg_enum")) // .flat_map(|attr| { .for_each(|attr| { attr.parse_nested_meta(|meta| { if meta.path.is_ident("alias") { let val = meta.value()?; let alias: Literal = val.parse()?; all_lits.push((alias.into(), id)); } if meta.path.is_ident("name") { let val = meta.value()?; let name: Literal = val.parse()?; all_lits[0] = (name.into(), id); } Ok(()) }) .unwrap(); }); all_lits.into_iter() }) .collect(); let len = all_variants.len(); let from_str_match = all_variants.iter().flat_map(|(lit, id)| { let pat: TokenStream = quote! { #lit | _ if s.eq_ignore_ascii_case(#lit) => Ok(#name::#id), }; pat.into_iter() }); let from_str_match = TokenStream::from_iter(from_str_match); let all_descriptions: Vec<(Vec, Vec)> = variants .iter() .map(|item| { let id = &item.ident; let description = item .attrs .iter() .filter_map(|attr| { let expr = match &attr.meta { Meta::NameValue(name_value) if name_value.path.is_ident("doc") => { Some(name_value.value.to_owned()) } _ => // non #[doc = "..."] attributes are not our concern // we leave them for rustc to handle { None } }; expr.and_then(|expr| { if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = expr { Some(s) } else { None } }) }) .collect(); let lit: TokenTree = Literal::string(&id.to_string()).into(); let mut all_names = vec![lit]; item.attrs .iter() .filter(|attr| attr.path().is_ident("arg_enum")) // .flat_map(|attr| { .for_each(|attr| { attr.parse_nested_meta(|meta| { if meta.path.is_ident("alias") { let val = meta.value()?; let alias: Literal = val.parse()?; all_names.push(alias.into()); } if meta.path.is_ident("name") { let val = meta.value()?; let name: Literal = val.parse()?; all_names[0] = name.into(); } Ok(()) }) .unwrap(); }); (all_names, description) }) .collect(); let display_match = variants.iter().flat_map(|item| { let id = &item.ident; let lit: TokenTree = Literal::string(&id.to_string()).into(); let pat: TokenStream = quote! { #name::#id => write!(f, #lit), }; pat.into_iter() }); let display_match = TokenStream::from_iter(display_match); let comma: TokenTree = Punct::new(',', proc_macro2::Spacing::Alone).into(); let array_items = all_variants .iter() .flat_map(|(tok, _id)| vec![tok.clone(), comma.clone()].into_iter()); let array_items = TokenStream::from_iter(array_items); let array_descriptions = all_descriptions.iter().map(|(names, descr)| { quote! { (&[ #(#names),* ], &[ #(#descr),* ]), } }); let array_descriptions = TokenStream::from_iter(array_descriptions); let len_descriptions = all_descriptions.len(); let ret: TokenStream = quote_spanned! { Span::call_site() => impl ::std::str::FromStr for #name { type Err = String; fn from_str(s: &str) -> ::std::result::Result { match s { #from_str_match _ => { let values = [ #array_items ]; Err(format!("valid values: {}", values.join(" ,"))) } } } } impl ::std::fmt::Display for #name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { #display_match } } } impl #name { #[allow(dead_code)] /// Returns an array of valid values which can be converted into this enum. pub fn variants() -> [&'static str; #len] { [ #array_items ] } #[allow(dead_code)] /// Returns an array of touples (variants, description) pub fn descriptions() -> [(&'static [&'static str], &'static [&'static str]); #len_descriptions] { [ #array_descriptions ] } } }; ret.into() } arg_enum_proc_macro-0.3.4/tests/enums.rs000064400000000000000000000046321046102023000164750ustar 00000000000000use arg_enum_proc_macro::ArgEnum; #[derive(ArgEnum, PartialEq, Debug)] pub enum Foo { Bar, /// Foo Baz, } #[test] fn parse() { let v: Foo = "Baz".parse().unwrap(); assert_eq!(v, Foo::Baz); } #[test] fn variants() { assert_eq!(&Foo::variants(), &["Bar", "Baz"]); } mod alias { use arg_enum_proc_macro::ArgEnum; #[derive(ArgEnum, PartialEq, Debug)] pub enum Bar { A, B, #[arg_enum(alias = "Cat")] C, } #[test] fn parse() { let v: Bar = "Cat".parse().unwrap(); assert_eq!(v, Bar::C); } #[test] fn variants() { assert_eq!(&Bar::variants(), &["A", "B", "C", "Cat"]); } } mod name { use arg_enum_proc_macro::ArgEnum; #[derive(ArgEnum, PartialEq, Debug)] pub enum Bar { A, B, #[arg_enum(name = "Cat", alias = "Feline")] C, } #[test] fn parse() { let v: Bar = "Cat".parse().unwrap(); assert_eq!(v, Bar::C); } #[test] fn variants() { assert_eq!(&Bar::variants(), &["A", "B", "Cat", "Feline"]); } } mod description { use arg_enum_proc_macro::ArgEnum; #[derive(ArgEnum, PartialEq, Debug)] pub enum Bar { /// This is A and it's description is a single line A, /// This is B and it's description contains " for no specific reason /// and is in two lines. B, /// This is C, normally known as "Cat" or "Feline" #[arg_enum(name = "Cat", alias = "Feline")] C, } #[test] fn descriptions() { let expected: [(&'static [&'static str], &'static [&'static str]); 3usize] = [ ( &["A"], &[" This is A and it's description is a single line"], ), ( &["B"], &[ " This is B and it's description contains \" for no specific reason", " and is in two lines.", ], ), ( &["Cat", "Feline"], &[" This is C, normally known as \"Cat\" or \"Feline\""], ), ]; assert_eq!(&Bar::descriptions(), &expected); } } mod ui { #[test] fn invalid_applications() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/complex-enum.rs"); t.compile_fail("tests/ui/derive-not-on-enum.rs"); } } arg_enum_proc_macro-0.3.4/tests/ui/complex-enum.rs000064400000000000000000000002721046102023000203700ustar 00000000000000use arg_enum_proc_macro::ArgEnum; pub enum Foo { Bar, /// Foo Baz, } #[derive(ArgEnum)] pub enum Complex { A, B(Foo), C { a: usize, b: usize }, } fn main() {} arg_enum_proc_macro-0.3.4/tests/ui/complex-enum.stderr000064400000000000000000000003501046102023000212440ustar 00000000000000error: proc-macro derive panicked --> $DIR/complex-enum.rs:9:10 | 9 | #[derive(ArgEnum)] | ^^^^^^^ | = help: message: Only enum with unit variants are supported! Variant Complex::B is not an unit variant arg_enum_proc_macro-0.3.4/tests/ui/derive-not-on-enum.rs000064400000000000000000000002011046102023000213770ustar 00000000000000use arg_enum_proc_macro::ArgEnum; #[derive(ArgEnum)] pub struct Complicated { pub foo: u8, pub bar: u8, } fn main() {} arg_enum_proc_macro-0.3.4/tests/ui/derive-not-on-enum.stderr000064400000000000000000000002421046102023000222630ustar 00000000000000error: proc-macro derive panicked --> $DIR/derive-not-on-enum.rs:3:10 | 3 | #[derive(ArgEnum)] | ^^^^^^^ | = help: message: Only enum supported