#proc-macro #macro-derive #attributes #proc-macro-attributes #parser

derive-attr-parser

非常简单的过程宏属性解析器

2个版本

0.1.1 2023年11月16日
0.1.0 2023年11月16日

#532 in 过程宏

MIT/Apache

21KB
341

衍生属性的简单解析器

代码太简单,无法编写文档。只需查看代码,一切都会明了。

过程宏中的典型使用

let input = parse_macro_input!(inputTokenStream as DeriveInput);
let ctx = derive_attr_parser::Ctxt::new();
const DEMO: derive_attr_parser::Symbol = derive_attr_parser::Symbol("demo");
let container = derive_attr_parser::from_ast(&ctx, input, DEMO);

完整演示代码

extern crate proc_macro;

use quote::quote;
use syn::{parse_macro_input, DeriveInput};
use derive_attr_parser::{Ctxt, from_ast, Symbol};

#[proc_macro_derive(DemoDerive, attributes(demo))]
pub fn simuples(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let mut input = parse_macro_input!(input as DeriveInput);
    demo_expand(&mut input)
        .unwrap_or_else(syn::Error::into_compile_error)
      .into()
}
const DEMO: Symbol = Symbol("demo");
fn demo_expand(input: &mut syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    let ctx = Ctxt::new();
    let cont = from_ast(&ctx, input, DEMO);
    ctx.check()?;
    eprintln!("{cont:#?}");

    //Do something with the info.
    //eg. Generate System Dynamics Code.
    Ok(quote!())
}

查看 Container, Field, [Val]

演示衍生用法

#[derive(DemoDerive)]
#[demo(
name = "test",
method = "system_dynamics",
ode_solver = "eula",
input_name = "BassInput",
output_name = "BassOutput"
)]
#[demo(input(name = "BassInput", ty = "struct"))]
#[demo(output(name = "BassOutput", ty = "struct"))]
pub struct Bass {
    #[demo(param(val = "10_000_f64"), input(from = "total_population"))]
    total_population: f64,
    #[demo(param(val = "0.015_f64"))]
    ad_effectiveness: f64,
    #[demo(param(val = "100_f64"))]
    contact_rate: f64,
    #[demo(param(val = "0.011_f64"))]
    sales_fraction: f64,
    #[demo(var(val = "potential_clients * ad_effectiveness"))]
    sales_from_ad: f64,
    #[demo(var(
    val = "clients * contact_rate * sales_fraction * potential_clients / total_population"
    ))]
    sales_from_wom: f64,

    #[demo(stock(val = "total_population"), output(to = "potential_clients"))]
    potential_clients: f64,
    #[demo(stock, output(to = "clients"))]
    clients: f64,

    #[demo(
    flow(
    from = "potential_clients",
    to = "clients",
    val = "sales_from_ad + sales_from_wom"
    ),
    output(to = "sales")
    )]
    sales: f64,
}

依赖关系

~280–730KB
~17K SLoC