Wing 语言 Map 遍历与 entries() 方法实战:从 map_entries 测试用例到 hangar 快照验证
Wing 语言 Map 遍历与 entries() 方法实战:从 map_entries 测试用例到 hangar 快照验证
导读
本文以仓库内 map_entries.test.w 的 sim 测试快照 为线索,完整剖析 Wing 语言 Map 数据结构的核心操作方法(entries()、has()、get()、size()),并结合 测试源码、tf-aws 编译快照 与 SDK 实现 解释其底层宏展开原理。读完本文,你将能够:熟练使用 Wing 的 Map 进行键值存取与遍历、理解 ArrayEntry 的类型结构、看懂 hangar 快照的生成方式,并掌握在 sim 目标下运行与验证 Map 行为的完整工作流。
一、快照文档解读:四个测试全部通过
hangar 快照 map_entries.test.w_test_sim.md 记录了 wing test -t sim 在 sim(本地模拟器)目标下的标准输出:
pass ─ map_entries.test.wsim » root/Default/test:check entries() when map has multiple entries
pass ─ map_entries.test.wsim » root/Default/test:check if map has entries
pass ─ map_entries.test.wsim » root/Default/test:get value from map
pass ─ map_entries.test.wsim » root/Default/test:iterate map using entries() method
Tests 4 passed (4)
Snapshots 1 skipped
Test Files 1 passed (1)
Duration <DURATION>
这条输出揭示了几个关键信息:
- 测试运行目标为
sim,对应wing test -t sim命令(见 generated_test_targets.ts 中platforms = ["sim"]与args = ["test"]的设定); - 测试用例名称为
root/Default/test:...,这是 Wing 测试树中每个test块的完整作用域路径; Tests 4 passed (4)表示 4 个测试全部通过;Duration <DURATION>中的占位符<DURATION>是 hangar 在生成快照时统一替换的耗时标记,用于保证快照在不同机器上可复现。
该快照对应的测试源码位于 tests/valid/map_entries.test.w,总共包含 4 个 test 块,正是快照中 4 条 pass 记录的来源。
二、测试源码逐行剖析:四个 test 块的意图
2.1 检查 Map 是否包含条目
let map = { "foo" => "hello" };
test "check if map has entries" {
assert(map.size() == 1);
assert(map.has("foo"));
assert(!map.has("bar"));
}
{ "foo" => "hello" }是 Wing 的 Map 字面量语法,=>将字符串键映射到值;该写法默认创建不可变 Map,值类型由内容推断为str;size()返回元素个数;has()判断指定键是否存在。
2.2 从 Map 取值
test "get value from map" {
assert(map.get("foo") == "hello");
}
get(key)返回指定键关联的值。注意:若键不存在,get()会抛出异常(错误信息形如Map does not contain key: "bye",见 map.test.w);如需安全取值应使用返回可空类型的tryGet()。
2.3 用 entries() 遍历 Map
test "iterate map using entries() method" {
// iterate over map entries
let entries = map.entries();
for x in map.entries() {
assert(x.key == "foo");
assert(x.value == "hello");
}
}
entries()返回Array<ArrayEntry>,其中ArrayEntry是一个含key: str与value: T两个字段的结构体(定义于 map.ts);- 因此可以直接用
for循环解出x.key/x.value访问每个条目的键与值。
2.4 多条目场景下的 entries() 长度
test "check entries() when map has multiple entries" {
let map = { "foo" => "hello", "bar" => "world" };
// check array length
assert(map.entries().length == 2);
}
- 该测试验证
entries()返回的数组长度与 Map 条目数一致(2 个条目 → 2 个ArrayEntry),覆盖多键值对场景。
三、Map 与 MutMap:不可变与可变的键值容器
Wing 标准库提供两类 Map,均定义于 packages/@winglang/sdk/src/std/map.ts:
| 类型 | 说明 | 关键方法 |
|---|---|---|
Map<T> |
不可变 Map,内容创建后不可修改 | size()、has()、get()、tryGet()、keys()、values()、entries()、copyMut() |
MutMap<T> |
可变 Map,可增删改 | 除左侧全部外,另有 set()、delete()、clear()、copy() |
两者的 entries() 均返回 MutArray<ArrayEntry>(API 文档见 docs/api/04-standard-library/std/map.md)。官方 by-example 教程 给出了两种写法的完整示例:
// immutable map
let configration = Map<str>{
"URL" => "https://winglang.io"
};
// mutable map
let listOfPrices = MutMap<num>{
"PRODUCT_1" => 100.00,
"PRODUCT_2" => 200.00,
"PRODUCT_3" => 300.00
};
// Map<num> is inferred
let values = {"a" => 1, "b" => 2}; // immutable map
// Change the values of the mutable map
listOfPrices.set("PRODUCT_1", 500);
log(configration.get("URL"));
log(Json.stringify(values.keys()));
log(Json.stringify(listOfPrices.get("PRODUCT_1")));
输出:
https://winglang.io
["a","b"]
500
在 tests/sdk_tests/std/map.test.w 中还能看到更完整的边界验证:copyMut() / copy() 的可变-不可变互转、delete() 返回布尔值、clear() 清空、tryGet() 在键缺失时返回 nil、以及 Map<str>{} == MutMap<str>{} 的相等性语义等。
四、entries() 的底层实现:宏展开的编译真相
Map.entries() 在 SDK 源码中并不是一段真正的运行时实现,而是一个编译期宏(map.ts 第 123-132 行):
/**
* Returns the entries from the map.
*
* @macro Object.entries($self$).map(([key, value]) => ({ key, value }))
*
* @returns the entries as Array<ArrayEntry>
*/
public entries(): ArrayEntry[] {
throw new Error("Macro");
}
类似的还有:
size()→@macro Object.keys($self$).lengthhas(key)→@macro ($args$ in ($self$))get(key)→@macro ((obj, key) => { if (!(key in obj)) throw new Error(...); return obj[key]; })($self$, $args$)tryGet(key)→@macro ($self$)?.[$args$]keys()→@macro Object.keys($self$)values()→@macro Object.values($self$)
也就是说,Wing 的 Map 在编译后直接以 JavaScript 对象承载,entries() 会被展开为 Object.entries(...).map(([key, value]) => ({ key, value })),这正是 ArrayEntry 结构({ key, value })的来源。
这一点可以在 tf-aws 编译快照 中得到铁证。编译产物 inflight.$Closure3-1.cjs 中:
async handle() {
const entries = $macros.__Map_entries(false, $map, );
for (const x of $macros.__Map_entries(false, $map, )) {
$helpers.assert($helpers.eq(x.key, "foo"), "x.key == \"foo\"");
$helpers.assert($helpers.eq(x.value, "hello"), "x.value == \"hello\"");
}
}
$macros.__Map_entries 就是 entries() 方法宏在 JS 端的展开实现,x.key / x.value 的访问方式与测试源码一一对应。同样,$Closure1 中可以看到 __Map_size、__Map_has 的展开,$Closure2 中可以看到 __Map_get 的展开:
$helpers.assert($helpers.eq($macros.__Map_size(false, $map, ), 1), "map.size() == 1");
$helpers.assert($macros.__Map_has(false, $map, "foo"), "map.has(\"foo\")");
$helpers.assert((!$macros.__Map_has(false, $map, "bar")), "!map.has(\"bar\")");
$helpers.assert($helpers.eq($macros.__Map_get(false, $map, "foo"), "hello"), "map.get(\"foo\") == \"hello\"");
而 main.tf.json 中仅包含一个空的 aws provider 配置(因为该测试没有创建任何云资源),preflight.cjs 则展示了 4 个 std.Test 的注册过程——每个 test 块被编译为一个 $ClosureN 闭包,通过 globalThis.$ClassFactory.new("@winglang/sdk.std.Test", ...) 挂载到测试树中。
五、宏展开的 lift 细节:闭包如何捕获 Map
preflight.cjs 中还有一个值得关注的点——闭包对 map 的捕获(lift)声明。每个 $Closure 的 _liftMap 精确声明了该闭包在 inflight 阶段会用到 map 的哪些方法:
// $Closure1: 用到 size 与 has
"handle": [ [map, [].concat(["size"], ["has"])] ],
// $Closure2: 用到 get
"handle": [ [map, ["get"]] ],
// $Closure3: 用到 entries
"handle": [ [map, ["entries"]] ],
这说明 Wing 的 inflight 权限模型是**按需提升(lift)**的:闭包只捕获其实际调用的 Map 方法,编译器据此生成最小化的数据面权限,避免过度授权。这一机制与仓库内 2024-03-14-explicit-lift-qualification.md 中描述的显式 lift 限定思路一脉相承。
六、hangar 快照体系:快照是如何生成与维护的
本文开篇引用的快照并非手写文档,而是由 hangar 工具链自动生成并沉淀到 tools/hangar/__snapshots__/ 目录下的测试基线:
- generate_tests.ts 扫描
tests/valid、tests/sdk_tests等目录下的.w文件,为每个文件生成对应的 vitest 用例,分别调用wing compile -t tf-aws与wing test -t sim; - generated_test_targets.ts 中:
compileTest()运行编译并收集target/*.tfaws/.wing下的产物(preflight.*、inflight.*、main.tf.json等),调用createMarkdownSnapshot()写入*_compile_tf-aws.md;testTest()在临时目录运行wing test -t sim,将 stdout 写入stdout.log并生成*_test_sim.md;
- 快照中的
<DURATION>占位符由 hangar 统一替换,保证输出不依赖机器性能;.map源码映射文件被显式排除,main.tf.json中的路径还会经过sanitize_json_paths()规范化处理。
因此,map_entries.test.w_test_sim.md 这类快照既是 CI 回归测试的基线,也是读者理解 Wing 测试输出格式、验证编译器行为的一手资料——修改 SDK 宏实现或编译器逻辑后,任何行为变化都会在此类快照中暴露。
七、类型约束与常见错误:invalid 测试的启示
与 valid 用例配对的 tests/invalid/map_entries.test.w 展示了 entries() 的类型错误用法:
let mapToNumber = { "foo" => 1, "bar" => 2 };
let someStr: str = mapToNumber.entries().at(0).value;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Expected type to be "str", but got "num" instead
这里 entries().at(0) 取到的是 ArrayEntry<num>,其 value 字段类型为 num,赋值给 str 变量会触发编译错误。这个用例说明:
entries()返回的ArrayEntry.value类型由 Map 的值类型参数T决定;- Wing 编译器在类型检查阶段即可拦截这类键值类型错配,无需等到运行时。
八、实战小结:Map 操作的最佳实践
结合测试源码、SDK 实现与编译产物,在 Wing 中使用 Map 可总结如下经验:
- 按需选择可变性:只读配置用
Map<T>,需要动态增删改的场景用MutMap<T>;set()/delete()/clear()仅存在于MutMap; - 取值先判断存在性:
get()对缺失键抛异常,tryGet()返回可空值,has()用于前置判断; - 遍历首选 entries():
for x in map.entries()同时拿到x.key与x.value,比keys()/values()分开取更高效直观; - 留意类型推导:Map 字面量
{ "a" => 1 }自动推断为Map<num>,entries()的value字段随之变为num,赋值目标需类型匹配; - 验证手段:将业务逻辑写入
test块,通过wing test -t sim在本地模拟器快速验证,行为基线可对照tools/hangar/__snapshots__/test_corpus/valid/下的同名快照。
如需进一步查阅 Map 全量 API,可参考 docs/api/04-standard-library/std/map.md;完整的 SDK 级行为验证见 tests/sdk_tests/std/map.test.w。