Debian Codegraph @

debian/rust-vendor/codspeed-divan-compat-macros/src/args.rs

raw
1 use itertools::Itertools;
2 use proc_macro::TokenStream;
3 use quote::{quote, ToTokens};
4 use syn::{
5 parse::{Parse, Parser},
6 Expr, Meta, MetaNameValue, Token, Type,
7 };
8
9 /// Values from parsed options shared between `#[divan::bench]` and
10 /// `#[divan::bench_group]`.
11 ///
12 /// The `crate` option is not included because it is only needed to get proper
13 /// access to `__private`.
14 #[derive(Default)]
15 pub(crate) struct AttrOptions {
16 pub(crate) types: Option<GenericTypes>,
17 pub(crate) crate_: bool,
18 pub(crate) other_args: Vec<Meta>,
19 }
20
21 #[allow(unreachable_code)]
22 impl AttrOptions {
23 pub fn parse(tokens: TokenStream) -> Result<Self, TokenStream> {
24 let mut attr_options = Self::default();
25
26 let attr_parser = syn::meta::parser(|meta| {
27 let Some(ident) = meta.path.get_ident() else {
28 return Err(meta.error("Unexpected attribute"));
29 };
30
31 let ident_name = ident.to_string();
32 let ident_name = ident_name.strip_prefix("r#").unwrap_or(&ident_name);
33
34 match ident_name {
35 // Divan accepts type syntax that is not parseable into syn::Meta out of the box,
36 // so we parse and rebuild the arguments manually.
37 "types" => {
38 attr_options.types = Some(meta.value()?.parse()?);
39 }
40 "crate" => {
41 attr_options.crate_ = true;
42 meta.value()?.parse::<Expr>()?; // Discard the value
43 }
44 "min_time" | "max_time" | "sample_size" | "sample_count" | "skip_ext_time" => {
45 // These arguments are ignored for codspeed runs
46 meta.value()?.parse::<Expr>()?; // Discard the value
47 }
48 "counters" => {
49 // Counters are not yet supported, but we parse them to avoid errors
50 eprintln!(
51 "Warning: Counter feature is not yet supported by codspeed-divan-compat"
52 );
53 meta.value()?.parse::<Expr>()?; // Discard the value
54 }
55 _ => {
56 let path = meta.path.clone();
57 let parsed_meta = if meta.input.is_empty() {
58 Meta::Path(path)
59 } else {
60 let value: syn::Expr = meta.value()?.parse()?;
61 Meta::NameValue(MetaNameValue {
62 path,
63 eq_token: Default::default(),
64 value: Expr::Verbatim(value.into_token_stream()),
65 })
66 };
67
68 attr_options.other_args.push(parsed_meta);
69 }
70 }
71
72 Ok(())
73 });
74
75 match attr_parser.parse(tokens) {
76 Ok(()) => {}
77 Err(error) => return Err(error.into_compile_error().into()),
78 }
79
80 Ok(attr_options)
81 }
82 }
83
84 /// Generic types over which to instantiate benchmark functions.
85 pub(crate) enum GenericTypes {
86 /// List of types, e.g. `[i32, String, ()]`.
87 List(Vec<proc_macro2::TokenStream>),
88 }
89
90 impl Parse for GenericTypes {
91 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
92 let content;
93 syn::bracketed!(content in input);
94
95 Ok(Self::List(
96 content
97 .parse_terminated(Type::parse, Token![,])?
98 .into_iter()
99 .map(|ty| ty.into_token_stream())
100 .collect(),
101 ))
102 }
103 }
104
105 impl ToTokens for GenericTypes {
106 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
107 match self {
108 Self::List(list) => {
109 let type_tokens = list.iter().cloned().map_into::<proc_macro2::TokenStream>();
110 tokens.extend(quote! { [ #(#type_tokens),* ] });
111 }
112 }
113 }
114 }