From 57ccdd5eadb21c9a011dd2c96bcd0c380dee2924 Mon Sep 17 00:00:00 2001 From: greg Date: Wed, 2 May 2018 19:30:34 -0700 Subject: [PATCH] Extract out attr parsing code into a separate function --- schala-codegen/src/lib.rs | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/schala-codegen/src/lib.rs b/schala-codegen/src/lib.rs index d878e66..2cbecfc 100644 --- a/schala-codegen/src/lib.rs +++ b/schala-codegen/src/lib.rs @@ -5,13 +5,28 @@ extern crate quote; extern crate syn; use proc_macro::TokenStream; -use syn::DeriveInput; +use syn::{Attribute, DeriveInput}; #[proc_macro] pub fn print_a_thing(_input: TokenStream) -> TokenStream { "println!(\"Invoked from a proc macro\");".parse().unwrap() } +fn extract_attribute_arg_by_name(name: &str, attrs: &Vec) -> Option { + use syn::{Meta, Lit, MetaNameValue}; + attrs.iter().map(|attr| attr.interpret_meta()).find(|meta| { + match meta { + &Some(Meta::NameValue(MetaNameValue { ident, .. })) if ident.as_ref() == name => true, + _ => false + } + }).and_then(|meta| { + match meta { + Some(Meta::NameValue(MetaNameValue { lit: Lit::Str(litstr), .. })) => Some(litstr.value()), + _ => None, + } + }) +} + #[proc_macro_derive(ProgrammingLanguageInterface, attributes(LanguageName, FileExtension, PipelineSteps))] pub fn derive_programming_language_interface(input: TokenStream) -> TokenStream { @@ -19,20 +34,7 @@ pub fn derive_programming_language_interface(input: TokenStream) -> TokenStream let name = &ast.ident; let attrs = &ast.attrs; - - let extracted_lang_name: Option = attrs.iter().map(|attr| attr.interpret_meta()).find(|meta| { - match meta { - &Some(syn::Meta::NameValue(syn::MetaNameValue { ident, .. })) if ident.as_ref() == "LanguageName" => true, - _ => false - } - }).and_then(|meta| { - match meta { - Some(syn::Meta::NameValue(syn::MetaNameValue { lit: syn::Lit::Str(litstr), .. })) => Some(litstr.value()), - _ => None, - } - }); - - let language_name = extracted_lang_name.unwrap(); + let language_name: String = extract_attribute_arg_by_name("LanguageName", attrs).unwrap(); println!("LANG NAME: {:?}", language_name);