知识卡片
用链接验证不会恐慌
#[no_panic] 是要求编译器证明函数不会 panic 的属性宏。它解析函数为 syn::ItemFn,把原函数体包进闭包,并在外面生成守卫和 Drop 实现。正常返回会执行 mem::forget(guard),所以守卫的析构函数不会被调用。当 panic 展开调用栈时,位于正常路径尾部的 forget 来不及执行,析构的代码路径就可能保留。
守卫的析构函数引用故意不提供定义的外部符号。若优化能排除析构路径,符号引用随之移除。若引用仍在,链接失败,符号名中带有函数名和提示。链接失败也可能表示编译器未能证明安全。按 crate 文档,这个检查依赖实际链接、能做出相应证明的优化配置和 panic = "unwind"。
相关卡片 [[属性宏包装异步入口]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Making fields public with attribute macros 用链接失败检查 panic 路径 · 查看原书依据
This library and others similar to it do a neat trick: they create a struct, implement Drop and call a nonexisting C function within the implementation, and add a forget call.
参考来源
- 位置:《Write Powerful Rust Macros》第04章《Making fields public with attribute macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-4.xhtml#p122)
- 结论依据:书中由 Dropper、panic 和 forget 的演示推出守卫可达性,清单源码表明函数签名保留而函数体被包装,并把诊断加入缺失符号名。项目文档核对构建边界。
- 原始内容:This library and others similar to it do a neat trick: they create a struct, implement Drop and call a nonexisting C function within the implementation, and add a forget call.