【问题标题】:How do I generate a macro from previous macro-generated code?如何从以前的宏生成代码生成宏?
【发布时间】:2021-05-20 17:34:48
【问题描述】:

为了创建一个使用泛型类型的结构的 pyo3 驱动的 Python 类,我想使用包装器来生成不需要为每个特定类型执行此操作的代码。

我创建了一个生成代码的宏,但我需要将我的宏生成的函数注册为 Python 模块的函数。

一种方法是跟踪宏中使用的标识以使用它们并使用另一个宏生成wrap_pyfunction,但我找不到任何相关内容。

(当然,任何其他生成代码的解决方案都会受到热烈欢迎)

我现在拥有的(简化的)代码:

macro_rules! create_python_function {
    ($name:ident, $objtype:expr) => {
        paste!{
            #[pyclass(unsendable)]
            pub struct [<$name PyIface>] {
                obj: GenericStruct<$objtype>,
            }

            impl [<$name PyIface>]{
                pub fn new() -> [<$name PyIface>]{
                    [<$name PyIface>] {}
                }
            }

            pub fn [<create_object_ $name>]() -> [<$name PyIface>]{
                [<$name PyIface>]::new()
            }
        }
    };
}

create_python_function!(name, SpecificType);

#[pymodule]
fn mymodule(_py: Python, m: &PyModule) -> PyResult<()> {
    /* I want to auto-generate this with macro
     * m.add_function(wrap_pyfunction!(create_object_name, m)?).unwrap(); 
     */
    Ok(())
}

【问题讨论】:

  • 您可以在宏定义中定义宏,调用外部宏后即可使用。内部宏定义可以使用外部宏定义的参数。虽然我不确定这是否是您需要的。
  • 不,但很有趣,谢谢。我想要的是调用一堆“create_python_function”宏,并在pymodule中只调用一个“wrap_created_python_functions”,它会为我之前调用的“create_python_function”的每个标识生成1行代码。我需要记住 create_python_function 宏中使用的所有 $name ident 并使用它来生成最终包装(希望我足够清楚)

标签: rust macros pyo3 rust-decl-macros


【解决方案1】:

宏不能共享它们的参数或状态。 如果您不想重复标识符,请将mymodule 定义移动到create_python_function 宏中并将宏更改为使用repetitions (The Rust Reference)

macro_rules! create_python_function {
    ($($name:ident => $objtype:ty),* $(,)?) => {
        $(
            paste! {
                #[pyclass(unsendable)]
                pub struct [<$name PyIface>] {
                    obj: GenericStruct<$objtype>,
                }

                impl [<$name PyIface>]{
                    pub fn new() -> [<$name PyIface>]{
                        [<$name PyIface>] { obj: todo!() }
                    }
                }

                pub fn [<create_object_ $name>]() -> [<$name PyIface>]{
                    [<$name PyIface>]::new()
                }
            }
        )*

        #[pymodule]
        fn mymodule(_py: Python, m: &PyModule) -> Result<(), ()> {
            $(
                paste! {
                    m.add_function(wrap_pyfunction!([<create_object_ $name>], m)?).unwrap();
                }
            )*
            Ok(())
        }
    };
}

struct Foo;
create_python_function!(
    foo => Foo,
    v => Vec<()>,
);

【讨论】:

  • 非常感谢,确实可以优雅地处理这个问题! Rust 宏是如此强大,我预计我错过了这样的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
相关资源
最近更新 更多