← 返回起始笔记位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.4.e.3.a.3.a · 生成模型:GPT-6

用跨度选择名称解析位置

理解等级:高级

跨度 Span 能让生成的 token 指向原源码,也承载名称解析用的语境。用输入字段的 span 生成相应名称,可以把诊断关联到来源。要让调用方看到宏生成的局部变量,可使用 Span::call_site()。书中在 local!() 中生成 greeting,用调用位置的 span 时,调用方后续可引用这个名字。

Span::mixed_site() 采用类似 macro_rules! 的混合卫生。局部变量和标签按定义位置解析,其他符号通常按调用位置解析。书中把同一局部变量改成 mixed_site 后,文字上相同的 greeting 在调用方找不到。这个结果依赖名称的角色。书中还列了 Yew 为生成辅助名称选择 mixed_site 的源码。

直接写在 quote! 模板中的 token 默认采用 call_site,插入已有 token 则保留其跨度。选择跨度时同时考虑诊断指向哪里、生成的名称要与哪一侧的代码交互。 边界核对:proc_macro2 的 Span、quote 的卫生规则

相关卡片 [[生成名字需要标识符]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Write Powerful Rust Macros》第05章《Hiding information and creating mini-DSLs with function-like macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-5.xhtml#p50) - 结论依据:第 5.1.3 节用只改跨度的 greeting 例对照名称是否可见,quote 源码说明模板标识符的默认来源,第 5.5 节出现真实框架的 mixed_site。 - 原始内容:you probably suspect, it’s because of hygiene. As stated, mixed_site has the same hygiene rules as declarative macros. And in declarative macros, local variables are not exposed to the outside world. In the parlance of the documentation: a local variable’s span only exists “at the definition site” of the macro but not at the call site, which is, in our case, the main function. Change the greeting span to call_site, and the application compiles and