Macros in 'when' clause don't capture variables
还没有人认领这个 Issue。
评估
调研方向
从 switch/when 模式匹配的宏展开路径开始,并将其与直接数组模式示例进行比较。重现所示的 $binop 情况,并跟踪展开后标识符是否被绑定;完成的标准是基于宏的模式能够像直接模式一样捕获 a、b 和 c,或者该行为被记录为符合预期。
由索引模型根据 Issue 内容生成。
描述
I want to have something at least resembling algebraic data types in Yuescript - these are called enums in Rust, variants in OCaml, tagged unions in C. These are types that you can construct and they carry the underlying variant and some fields that the variant has. An example of this in Rust can be seen here: https://doc.rust-lang.org/rust-by-example/custom_types/enum.html
To that end I've been trying to use existing pattern matching functionality and macros to get this behavior. For the sake of example, let's say we want to encode variants of an enum as an array ['VariantName', ...fields], for example:
lang =
BinOp: (lhs, op, rhs) => ['BinOp', lhs, op, rhs]
Var: (name, expr) => ['Var', name, expr]
Const: (val) => ['Const', val]
Then I'd like to do pattern matching on different variants, but have a bit nicer syntax:
macro binop = (x,y,z) -> {
code: "['Binop', #{x}, #{y}, #{z}]"
type: "yue"
}
switch e
when $binop a,b,c
print "foo"
But this compiles to:
if {
'Binop',
a,
b,
c
} == e then
return print("foo")
end
But this isn't what I want, as it does not assign a, b, c variables for me to use inside the 'when' block. If I use the expected output of the macro directly:
switch e
when ['Binop', a, b, c]
print "bar"
I get what I expected - a, b, c are assigned values of e[2..4]:
local _type_0 = type(e)
local _tab_0 = "table" == _type_0 or "userdata" == _type_0
if _tab_0 then
local a = e[2]
local b = e[3]
local c = e[4]
if 'Binop' == e[1] and a ~= nil and b ~= nil and c ~= nil then
return print("bar")
end
end
This behavior is a bit unexpected, seems like macro evaluation happens at some later stage of compilation so instead of variable capture I get table comparison. Is this a bug or working as intended?
- 主要语言
- Lua
- 星标
- 620
- 派生
- 45
- 平均合并
- 9 小时 5 分钟
- 30 天内合并 PR
- 1
环境准备
这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
IppClub/YueScript 的其他 Issue
-
难度 3/5 1-2 天 新手友好度 64/100
-
难度 3/5 1-2 天 新手友好度 35/100
-
难度 5/5 一周以上 新手友好度 25/100
-
难度 5/5 一周以上 新手友好度 25/100
-
难度 5/5 一周以上 新手友好度 35/100
查看 IppClub/YueScript 的全部 Issue
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 82/100
维护者通常 2 天内回复
-
follow-up
难度 2/5 1-3 小时 新手友好度 78/100
ksysoev/duet.nvim#265 · 1 条评论 ·
维护者通常 1 天内回复
-
bug: accuracy
难度 2/5 1-3 小时 新手友好度 72/100
PathOfBuildingCommunity/PathOfBuilding#10649 ·
维护者通常 1 天内回复
-
reMarkable
难度 2/5 1-3 小时 新手友好度 78/100
koreader/koreader#16485 · 1 条评论 ·
维护者通常 1 天内回复
-
bug
难度 2/5 1-3 小时 新手友好度 76/100
nvim-orgmode/orgmode#1213 ·