From fd4c447a2d9f847c5b0e4de183e4ee95fcbda677 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Sat, 23 Nov 2024 23:25:14 +0000 Subject: [PATCH] move attribute argument extractor to utils Signed-off-by: Jason Volk --- src/macros/config.rs | 47 ++++++-------------------------------------- src/macros/utils.rs | 34 +++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 42 deletions(-) diff --git a/src/macros/config.rs b/src/macros/config.rs index d7f11535..2934a0b2 100644 --- a/src/macros/config.rs +++ b/src/macros/config.rs @@ -1,9 +1,4 @@ -use std::{ - collections::{HashMap, HashSet}, - fmt::Write as _, - fs::OpenOptions, - io::Write as _, -}; +use std::{collections::HashSet, fmt::Write as _, fs::OpenOptions, io::Write as _}; use proc_macro::TokenStream; use proc_macro2::Span; @@ -13,7 +8,10 @@ use syn::{ ItemStruct, Lit, Meta, MetaList, MetaNameValue, Type, TypePath, }; -use crate::{utils::is_cargo_build, Result}; +use crate::{ + utils::{get_simple_settings, is_cargo_build}, + Result, +}; const UNDOCUMENTED: &str = "# This item is undocumented. Please contribute documentation for it."; @@ -29,7 +27,7 @@ pub(super) fn example_generator(input: ItemStruct, args: &[Meta]) -> Result Result<()> { - let settings = get_settings(args); + let settings = get_simple_settings(args); let filename = settings .get("filename") @@ -120,39 +118,6 @@ fn generate_example(input: &ItemStruct, args: &[Meta]) -> Result<()> { Ok(()) } -fn get_settings(args: &[Meta]) -> HashMap { - let mut map = HashMap::new(); - for arg in args { - let Meta::NameValue(MetaNameValue { - path, - value, - .. - }) = arg - else { - continue; - }; - - let Expr::Lit( - ExprLit { - lit: Lit::Str(str), - .. - }, - .., - ) = value - else { - continue; - }; - - let Some(key) = path.segments.iter().next().map(|s| s.ident.clone()) else { - continue; - }; - - map.insert(key.to_string(), str.value()); - } - - map -} - fn get_default(field: &Field) -> Option { for attr in &field.attrs { let Meta::List(MetaList { diff --git a/src/macros/utils.rs b/src/macros/utils.rs index e4ffc622..23c4c16f 100644 --- a/src/macros/utils.rs +++ b/src/macros/utils.rs @@ -1,7 +1,39 @@ -use syn::{parse_str, Expr, Generics, Lit, Meta}; +use std::collections::HashMap; + +use syn::{parse_str, Expr, ExprLit, Generics, Lit, Meta, MetaNameValue}; use crate::Result; +pub(crate) fn get_simple_settings(args: &[Meta]) -> HashMap { + args.iter().fold(HashMap::new(), |mut map, arg| { + let Meta::NameValue(MetaNameValue { + path, + value, + .. + }) = arg + else { + return map; + }; + + let Expr::Lit( + ExprLit { + lit: Lit::Str(str), + .. + }, + .., + ) = value + else { + return map; + }; + + if let Some(key) = path.segments.iter().next().map(|s| s.ident.clone()) { + map.insert(key.to_string(), str.value()); + } + + map + }) +} + pub(crate) fn is_cargo_build() -> bool { std::env::args() .find(|flag| flag.starts_with("--emit"))