知识卡片
Tokio宏生成运行时包装
书中所读 Tokio 版本的 #[tokio::main] 解析函数和属性选项,校验函数需要 async、名为 main 的入口无参数,再根据配置生成 runtime。生成的函数签名去掉 async,在函数执行时创建所选 runtime,并用 block_on 运行原函数体对应的 future。
#[tokio::test] 能复用部分输入处理和生成逻辑,在输出中按需添加测试属性。书中还展示生成代码时调节 Clippy 诊断,因为调用方难以修改宏自己生成的 expect 等表达式。清单采用旧版 syn 的 API,核心机制是生成同步外壳和异步执行逻辑。
相关卡片 [[同步宏等待异步执行]]、[[诊断提示正确的属性写法]]。
结构图:
flowchart TD
A["带属性的 async 函数"] --> B["解析 ItemFn 和属性选项"]
B --> C["验证签名及 runtime 配置"]
C --> D["输出去掉 async 的同步函数"]
D --> E["应用运行时创建 Tokio runtime"]
E --> F["block_on 执行原函数体对应的 future"]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Macros and the outside world 真实 crate 如何分发和展开宏 · 查看原书依据
First, the signature of the input is modified, removing the async. This is because Rust does not allow its main functions to be asynchronous. So, after removing the async, Tokio builds a Runtime and blocks on the existing code (contained within body), removing the need for asynchronicity.
参考来源
- 位置:《Write Powerful Rust Macros》第10章《Macros and the outside world》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-10.xhtml#p127)
- 结论依据:原文解析了该宏从函数签名到输出的变换,清单 10.24 显示运行时构造与 block_on 调用。
- 原始内容:First, the signature of the input is modified, removing the async. This is because Rust does not allow its main functions to be asynchronous. So, after removing the async, Tokio builds a Runtime and blocks on the existing code (contained within body), removing the need for asynchronicity.