From fdf68463d959405704be66ebf62c83fe9fea0c17 Mon Sep 17 00:00:00 2001 From: p0lunin Date: Mon, 24 Feb 2020 17:55:46 +0200 Subject: [PATCH] added impl_parse function --- src/lib.rs | 48 +++++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 186ca75f..4e445232 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -61,33 +61,17 @@ pub fn derive_telegram_command_enum(tokens: TokenStream) -> TokenStream { let fn_try_from = impl_try_parse_command(&variants, &variant_infos, &command_enum); let fn_descriptions = impl_descriptions(&variant_infos, &command_enum); + let fn_parse = impl_parse(); - let expanded = quote! { + let trait_impl = quote! { impl BotCommand for #ident { #fn_try_from #fn_descriptions - fn parse(s: &str, bot_name: N) -> Option<(Self, Vec<&str>)> - where - N: Into - { - let mut words = s.split_whitespace(); - let mut splited = words.next()?.split('@'); - let command_raw = splited.next()?; - let bot = splited.next(); - let bot_name = bot_name.into(); - match bot { - Some(name) if name == bot_name => {} - None => {} - _ => return None, - } - let command = Self::try_from(command_raw)?; - Some((command, words.collect())) - } + #fn_parse } }; - //for debug - //println!("{}", &expanded.to_string()); - TokenStream::from(expanded) + + TokenStream::from(trait_impl) } fn impl_try_parse_command(variants: &[&Variant], infos: &[Command], global: &CommandEnum) -> impl ToTokens { @@ -127,6 +111,28 @@ fn impl_descriptions(infos: &[Command], global: &CommandEnum) -> impl ToTokens { } } +fn impl_parse() -> impl ToTokens { + quote! { + fn parse(s: &str, bot_name: N) -> Option<(Self, Vec<&str>)> + where + N: Into + { + let mut words = s.split_whitespace(); + let mut splited = words.next()?.split('@'); + let command_raw = splited.next()?; + let bot = splited.next(); + let bot_name = bot_name.into(); + match bot { + Some(name) if name == bot_name => {} + None => {} + _ => return None, + } + let command = Self::try_from(command_raw)?; + Some((command, words.collect())) + } + } +} + fn get_enum_data(input: &DeriveInput) -> Result<&syn::DataEnum, TokenStream> { match &input.data { syn::Data::Enum(data) => Ok(data),