是否可以在 Rust 的过程宏中存储​​状态? [英] Is it possible to store state within Rust's procedural macros?

查看:63
本文介绍了是否可以在 Rust 的过程宏中存储​​状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以构建一个不输出任何内容而是存储状态以构建列表的宏,然后再构建一个实际使用该数据的宏?

Is it possible to build a macro that doesn't output anything but instead stores state to build up a list and then a second macro that will then actually use that data?

例如:

trait SomeTrait {}

#[derive(mark)]
struct Person {}

impl SomeTrait for Person {}

#[derive(mark)]
struct Item {}

impl SomeTrait for Item  {}

#[derive(mark)]
struct Object {}

impl SomeTrait for Object {}

create_mapper! // this then outputs the below function
//assuming for the fact that data is loaded correctly before this macro is used

fn select_item(kind: String) -> impl SomeTrait {
    match kind {
        "person" => Person,
        "item" => Item,
        "object" => Object,        
    }
}

推荐答案

目前没有官方支持的方式来存储可由两个不同的 proc 宏调用使用的状态.我创建了这个非常相关的问题,其中讨论了这个问题.

Currently there is no officially supported way to store state that can be used by two different proc macro invocations. I created this very related issue where this problem is discussed.

存储状态当然是可能的,但只是以一种hacky的方式.例如,您可以将所有状态序列化为 /tmp/my-state.或者您可以尝试使用 static 全局变量.但即使这现在有效,也不能保证将来有效.另一个问题:由于增量编译,不能保证所有 proc 宏调用都实际执行.因此,如果您有一个生成状态的宏和一个读取它的宏,如果第一个没有执行,就会发生非常奇怪的事情.所以技术上可以存储全局状态,但不可取.

Storing state is certainly possible, but just in a hacky way. You could, for example, serialize all your state into /tmp/my-state. Or you could try using static global variables. But even if this works now, this is not guaranteed to work in the future. Another problem: due to incremental compilation, it is not guaranteed that all of your proc macro invocations are actually executed. So if you have one macro that generates the state and one that reads it, if the first is not executed, really strange things happen. So it is technically possible to store global state, but it's not advisable.

在上面链接的问题中,您可以看到 MSleepyPanda 提出了一个可能的解决方案,但我们远未实现.

In the issue linked above, you can see that MSleepyPanda proposed a possible solution, but we are far from having this implemented.

这篇关于是否可以在 Rust 的过程宏中存储​​状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆