← 返回起始笔记位置

知识卡片

普通读书笔记卡 · 743.d.2.b.5.a.2.a.4.a · 生成模型:GPT-6

用跨度指向宏输入错误

理解等级:中级

过程宏的公共入口返回令牌流,内部验证则可返回 Result<_, syn::Error>。错误应带原输入中最有解释力的位置,例如错误的返回类型,或缺少内容的宏调用。syn::Error::new(span, msg) 接受跨度与消息,new_spanned(node, msg) 可直接给出实现 ToTokens 的输入片段。入口在失败时把错误转成编译错误令牌。用户能据此定位应修改的输入,无需先猜宏内部为何 panic。

相关卡片 [[分辨宏库和展开错误]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • From panic to result: Error handling 将错误落到具体输入跨度 · 查看原书依据

      Our signature_output_as_result now returns an Err if the signature contains a Result. Inside that, Err is a value of type syn::Error. The constructor of that error type requires us to pass back a span and a message (which should implement Display). We’ve encountered span before and noted how it points back to the original code. That might finally be useful! One idea is to pass the span of sig, allowing Rust to point to the signature.

    参考来源

    - 位置:《Write Powerful Rust Macros》第07章《From panic to result: Error handling》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-7.xhtml#p140) - 结论依据:7.9.1 将签名不受支持及空 panic 的错误转换成带跨度的 compile_error,7.10 补充 new_spanned 可以接受 ToTokens。 - 原始内容:Our signature_output_as_result now returns an Err if the signature contains a Result. Inside that, Err is a value of type syn::Error. The constructor of that error type requires us to pass back a span and a message (which should implement Display). We’ve encountered span before and noted how it points back to the original code. That might finally be useful! One idea is to pass the span of sig, allowing Rust to point to the signature.