简介
Puddi 是一门静态类型、面向表达式的语言,编译目标是 WebAssembly。同一套语法可以用于浏览器、WASI 运行时和插件宿主。程序使用 WebAssembly 引擎的垃圾回收功能 WasmGC,通过组件模型与宿主交互。
@derive(Eq, Show)
struct Todo {
title: Str
var done: Bool
}
fn main() {
let todos = [Todo { title: "spec", done: true }, Todo { title: "compiler", done: false }]
let pending = todos.filter(|t| !t.done)
print("{pending.len()} of {todos.len()} left")
}
1 of 2 left
语言概览
| 主题 | Puddi |
|---|---|
| 产物 | WebAssembly,浏览器使用 JavaScript 加载器 |
| 宿主 | browser、wasi(WASI 0.3)、plugin |
| 内存管理 | WasmGC |
| 类型 | 静态类型,局部类型推断 |
| 多态 | 泛型、名义特征和 dyn Trait |
| 缺失值与错误 | Option、Result、?、AnyErr;panic 触发陷阱 |
| 可变性 | let 与 var;逐字段声明可变性 |
| 数值 | Int 为 32 位有符号整数,溢出触发陷阱,无损拓宽可隐式进行 |
| 并发 | async fn、.await、结构化任务作用域与隔离的工作线程 |
| 工具链 | pud 命令、pud.toml 包清单与基于 Git 的包 |
阅读路线
| 我想 | 从这里开始 |
|---|---|
| 跑通第一个程序 | 安装 → 第一个程序 → 内置示例 |
| 学习语法和类型 | 从绑定与值开始阅读语言指南 |
| 在网页里运行 | 浏览器与标准库 |
| 给现有宿主编写插件 | 插件与 WIT 导入 |
| 查命令或解决错误 | pud 命令与故障排查 |
| 参与开发 | 编译器开发与参与贡献 |
本书以首个正式发行版 Puddi 0.1 为基线。中英文完整示例由同一发行版工具链检查。语言规范仍是草案,0.x 版本之间可能变化。查看语言规范、实现状态和更新日志可了解各自的版本范围。
获取帮助
- 问题和想法:Puddi Discussions
- 编译器和工具链问题:Puddi Issues
- 文档问题:文档仓库 Issues或页面上方的编辑入口
安装
pud 是一个独立的可执行文件,包含编译器、格式化器、包管理器和 wasi 目标的 WebAssembly 运行时。
安装脚本
macOS 和 Linux 支持 x86_64 和 arm64:
curl -fsSL https://raw.githubusercontent.com/puddi-lang/puddi/main/install.sh | sh
Windows 请在 PowerShell 中运行:
irm https://raw.githubusercontent.com/puddi-lang/puddi/main/install.ps1 | iex
脚本下载最新发行版,校验 SHA-256 后将 pud 安装到 ~/.pud/bin,并把目录加入 PATH。Unix 上会更新存在的 shell 配置,Windows 上会更新用户级 PATH。安装后打开新终端,或按脚本输出刷新环境。
| 环境变量 | 用途 |
|---|---|
PUD_VERSION | 安装指定版本,例如 v0.1.2;默认取最新发行版 |
PUD_INSTALL | 指定安装目录,默认 ~/.pud |
PUD_NO_MODIFY_PATH | 设为 1 时保留 shell 配置与 PATH |
curl -fsSL https://raw.githubusercontent.com/puddi-lang/puddi/main/install.sh | PUD_VERSION=v0.1.2 sh
升级时重新运行安装脚本。卸载时移除已安装的可执行文件,以及脚本向 shell 配置或 Windows 用户 PATH 写入的路径。使用过 PUD_INSTALL 的话,请从对应目录移除。
发行版压缩包
每个发行版为以下平台提供压缩包、各自的 .sha256 文件以及汇总的 SHA256SUMS。
| 压缩包 | 平台 |
|---|---|
pud-x86_64-unknown-linux-gnu.tar.gz | Linux x86_64,glibc 2.35 或更新版本 |
pud-aarch64-unknown-linux-gnu.tar.gz | Linux arm64,glibc 2.35 或更新版本 |
pud-x86_64-apple-darwin.tar.gz | Intel Mac |
pud-aarch64-apple-darwin.tar.gz | Apple 芯片的 Mac |
pud-x86_64-pc-windows-msvc.zip | Windows x64,也可在 Windows arm64 上运行 |
解压后将 pud 或 pud.exe 放入 PATH 中的任一目录。
从源码安装
使用当前稳定版 Rust:
cargo install --locked --git https://github.com/puddi-lang/puddi --tag v0.1.2
加上 --no-default-features 可省去内嵌运行时,缩短编译时间。此时用 pud build 构建组件,再交给兼容的外部 WASI 0.3 宿主运行。详见构建目标。
Node.js
pud test 和 browser 目标的工具链路径需要 Node.js 22 或更新版本。异步代码需要 JSPI,Node.js 24 默认启用它。内嵌的 WASI 和插件运行时无需 Node.js。遇到宿主功能缺失时可查阅故障排查。
确认安装
pud --version
第一个 Puddi 程序
运行单文件
无需创建包便可运行单个文件。将以下代码保存为 hello.pud:
fn main() {
let name = "Puddi"
print("Hello, {name}!")
}
Hello, Puddi!
运行它:
pud run hello.pud
pud run 会先生成 WASI 组件,再用内嵌的 WebAssembly 运行时执行。
fn main()是入口函数let声明一个绑定,此处推断出类型Str- 双引号字符串可用花括号插入表达式,例如
"{name}"或"{1 + 2}" - 通常换行结束一条语句,也可以用分号分隔
参数与退出状态
通过 std.env 读取命令行参数。main 可以返回 Result,返回 Err 时会输出错误并以失败状态退出。
import std.env
fn main() -> Result<(), Str> {
let args = env.args()
let Some(who) = args.get(1) else {
return Err("usage: greet <name>")
}
print("Hello, {who}!")
Ok(())
}
pud run greet.pud -- Ada
-- 后的内容原样传给程序。env.args() 的第一项是程序名。
只检查类型
pud check hello.pud # type-check only
pud fmt hello.pud # format in the official style
接下来可把单文件变成一个包。
包
一个包是同时包含 pud.toml 清单和 src/ 目录的目录。
pud new hello
cd hello
pud run
pud new 创建以下结构:
hello/
├── pud.toml
└── src/
└── main.pud
清单示例:
[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"
在包内运行命令时,pud 会从当前目录向父目录查找 pud.toml。因此 pud run、pud test 和 pud build 通常无需路径参数。
模块
每个文件是一个模块,模块名由 src/ 下的相对路径确定。src/main.pud 是程序根模块,库通常用 src/lib.pud。src/geometry.pud 对应 geometry,src/net/url.pud 对应 net.url。
// src/geometry.pud
pub struct Point {
pub x: Float
pub y: Float
}
pub fn distance(a: Point, b: Point) -> Float {
((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)).sqrt()
}
// src/main.pud
import geometry
import geometry.{Point}
fn main() {
let d = geometry.distance(Point { x: 0.0, y: 0.0 }, Point { x: 3.0, y: 4.0 })
print("{d}")
}
声明默认仅在所属模块内可见。使用 pub 将它公开。详见模块。
构建
pud build # target/wasi/hello.wasm
pud build --target browser # target/browser/hello.wasm and puddi.mjs
pud run --target browser # build and serve on http://127.0.0.1:8000
组件输出到 target/<target>/,创建包时生成的 .gitignore 已排除 target/。各目标的输出文件参见构建目标。
添加依赖
pud add github.com/someone/lib@1.2
命令更新 pud.toml,并把解析出的提交记录到 pud.lock。请将锁文件纳入版本控制。详见依赖。
测试
test 块可以与被测代码放在同一个文件中:
fn add(a: Int, b: Int) -> Int { a + b }
test "addition" {
assert_eq(add(2, 2), 4)
}
pud test 编译并执行测试,每个测试都在新的实例中运行。详见测试。
内置示例
编译器仓库提供四个小型示例包。先安装 pud,再克隆仓库。下表中的命令从仓库根目录开始执行。
| 包 | 内容 | 命令 |
|---|---|---|
| todo | 读取 JSON 与处理错误 | cd examples/todo 后运行 pud run |
| wordfreq | 读取标准输入并用映射统计词频 | printf 'a b a\n' | pud run examples/wordfreq |
| plugin | 实现自定义 WIT world 的导出 | pud build examples/plugin --target plugin |
| plugin-host | 在一个组件中使用多种宿主能力 | pud build examples/plugin-host --target plugin |
todo 在进程工作目录读取 todos.json,会输出 2 of 4 left。wordfreq 输出 a 出现 2 次、b 出现 1 次。两个插件分别在各自包目录中生成 target/plugin/plug.wasm 和 target/plugin/plugin-host.wasm。
需要实际调用插件时,可照着插件入门运行。plugin 示例的 greet 导出需要宿主提供 demo:host/log,而 classify 不会调用该接口。
绑定与值
let 与 var
let 声明不可重新赋值的绑定,var 声明可以重新赋值的绑定。
fn main() {
let greeting = "hello"
var count = 0
count += 1
count = count * 10
print("{greeting} {count}")
}
hello 10
局部绑定的类型通常由编译器推断。需要注明类型或缺少推断依据时,把类型写在名称后面:
fn main() {
let ratio: Float = 1
let names: List<Str> = []
print("{ratio} {names}")
}
1.0 []
给 let 绑定重新赋值会导致编译错误:
fn main() {
let total = 1
total = 2
}
引用值
结构体、枚举和集合是引用值。赋值或传参共享同一个对象,操作不会复制对象。
fn main() {
let a = [1, 2]
let b = a
b.push(3)
print("{a}")
print("{same(a, b)}")
}
[1, 2, 3]
true
let 固定的是绑定本身。对象能否修改由类型决定,例如 List 可以增删元素,结构体只有声明为 var 的字段才允许重新赋值。详见结构体与枚举。
== 通过 Eq 比较值。same(a, b) 判断两个引用是否指向同一个对象。
表达式
块、if、match 和 loop 都是表达式。块末尾的表达式给出块的值。
fn main() {
let x = 7
let size = {
let doubled = x * 2
if doubled > 10 { "big" } else { "small" }
}
print(size)
}
big
换行与语句
换行通常结束语句,也可以用 ; 在同一行分隔语句。行尾是二元运算符或逗号、( 或 [ 尚未匹配,或者下一行从 . 开始时,表达式会续到下一行。
fn main() {
let price = 3
let count = 4
let total = price * count +
2
let words = ["a", "bb", "ccc"]
.map(|w| w.to_upper())
print("{total} {words}"); print("done")
}
14 ["A", "BB", "CCC"]
done
注释
// a line comment
/* a block comment /* which may nest */ */
/// a doc comment, attached to the next declaration and read by `pud doc`
命名
类型、特征和枚举变体使用 UpperCamelCase,函数、变量、字段和模块使用 snake_case,常量使用 SCREAMING_SNAKE_CASE。
const MAX_RETRIES: Int = 3
fn main() {
print("up to {MAX_RETRIES} retries")
}
up to 3 retries
常量初始化必须是常量表达式,例如字面量、其他常量、对它们进行算术或比较,以及结构体、元组和枚举构造。
数值
| 类型 | 含义 |
|---|---|
Int | 32 位有符号整数,与 I32 相同 |
I8 I16 I32 I64 | 有符号整数 |
U8 U16 U32 U64 | 无符号整数 |
Float | 64 位浮点数,与 F64 相同 |
F32 F64 | 浮点数 |
上下文没有要求其他类型时,整数字面量默认为 Int,浮点字面量默认为 Float。数字可用 _ 分组,整数可用 0x、0b 和 0o 前缀。超出类型范围的字面量会导致编译错误。
fn main() {
let a = 1_000
let mask: U8 = 0xFF
let big: I64 = 3_000_000_000
let f = 2.5e-3
print("{a} {mask} {big} {f}")
}
1000 255 3000000000 0.0025
溢出与除法
整数溢出、除以零或对零取余会触发陷阱。整数除法向零截断,余数与被除数同号。
fn main() {
print("{-7 / 2} {-7 % 2}")
let x: U8 = 250
print("{x.wrapping_add(10)} {x.saturating_add(10)} {x.checked_add(10)}")
}
-3 -1
4 255 None
需要不同的溢出行为时,可使用 wrapping_*、saturating_* 或 checked_* 方法。
隐式拓宽
只要目标类型明确且转换总是无损,就可以隐式拓宽,例如绑定带类型标注、函数实参和返回值、字段初始化及集合元素。
fn average(total: Float, n: Float) -> Float { total / n }
fn main() {
let n: Int = 4
let wide: I64 = n
let small: U8 = 200
print("{average(10, n)} {wide + 1} {small + n}")
}
2.5 5 204
二元运算的数值类型不同时,两边会拓宽到能精确容纳双方的最窄公共类型。U8 + Int 的结果为 Int。I64 与 U64 或 I64 与 Float 没有这样的公共类型,编译会失败。I64 和 U64 都不会隐式转成浮点数,因为 F64 无法精确表示全部 64 位整数。
| 原类型 | 可拓宽到 |
|---|---|
I8 | I16 I32 I64 F32 F64 |
I16 | I32 I64 F32 F64 |
I32 | I64 F64 |
U8 | U16 U32 U64 I16 I32 I64 F32 F64 |
U16 | U32 U64 I32 I64 F32 F64 |
U32 | U64 I64 F64 |
F32 | F64 |
显式窄化
可能丢失信息的转换要调用方法。to_<type>() 返回 Option,转换失败时为 None。truncate_to_int() 与 round_to_int() 等方法明确指明如何截去小数或取整。
fn main() {
let big: I64 = 5_000_000_000
let fits: I64 = 42
print("{big.to_int()} {fits.to_int()}")
print("{3.7.truncate_to_int()} {3.7.round_to_int()}")
}
None Some(42)
3 4
浮点数
浮点类型提供 sqrt、pow、abs、floor、ceil、round、sin、cos、ln 等方法。std.math 也提供对应函数和 math.PI 等常量。输出保留能还原原数值的最短表示,没有小数部分的浮点数仍保留 .0。
fn main() {
let x = 2.0
print("{x.sqrt()} {0.1 + 0.2} {x.pow(10.0)}")
}
1.4142135623730951 0.30000000000000004 1024.0
解析字符串
fn main() {
print("{"42".parse_int()} {"x".parse_int()} {"1.5".parse_float()}")
}
Some(42) None Some(1.5)
字符串与字符
Str
Str 是不可变的 Unicode 字符串。字面量使用双引号,花括号内可插入实现了 Show 的表达式。普通花括号写作 \{ 和 \}。
fn main() {
let name = "Ada"
let unread = 2
print("hi {name}, you have {unread + 1} messages")
print("a literal \{brace\}")
print("tab\tnewline\\n quote\" smile \u{1F600}")
}
hi Ada, you have 3 messages
a literal {brace}
tab newline\n quote" smile 😀
支持的转义为 \n \r \t \0 \\ \" \' \{ \} \u{...}。
字符串长度与索引
字节数、码点数和可见字符数有不同含义。Str 不提供整数索引或通用的 len(),请明确选择要计算的单位。
fn main() {
let s = "héllo👋🏽"
print("{s.utf8_len()} bytes")
print("{s.chars().count()} code points")
print("{s.graphemes().count()} graphemes")
}
14 bytes
7 code points
6 graphemes
chars() 遍历 Unicode 码点,产生 Char。graphemes() 按字素簇遍历,产生 Str。0.1 的字素分割是近似实现,详见实现状态。
查找与切片
字符串位置用 StrIndex 表示。从 find、rfind、start()、end() 取得索引,或用 advance(i, n) 与 next_index(i) 按码点移动。索引只适用于生成它的字符串。
fn main() {
let line = "key=value"
match line.find("=") {
Some(i) -> {
print(line.slice_to(i))
let after = line.advance(i, 1).unwrap()
print(line.slice_from(after))
}
None -> print("no =")
}
if let Some((k, v)) = line.split_once("=") {
print("{k} -> {v}")
}
}
key
value
key -> value
常用方法
fn main() {
let s = " Hello, World "
let t = s.trim()
print(t.to_lower())
print("{t.contains("World")} {t.starts_with("He")} {t.ends_with("!")}")
print(t.replace("World", "Puddi"))
print("{"a,b,,c".split(",")}")
print("{"one two three".split_whitespace()}")
print(["x", "y", "z"].join("-"))
print("ab".repeat(3))
}
hello, world
true true false
Hello, Puddi
["a", "b", "", "c"]
["one", "two", "three"]
x-y-z
ababab
还有 lines、trim_start、trim_end、rfind、slice、is_empty、parse_int、parse_float 和 to_bytes 等方法。+ 可连接两个字符串。
拼接字符串
用 StrBuilder 逐段构建字符串。
fn main() {
let b = StrBuilder.new()
for i in 0..3 {
b.push("item {i};")
}
b.push_char('!')
print(b.to_str())
}
item 0;item 1;item 2;!
Char
Char 是一个 Unicode 标量值,使用单引号,例如 'a'、'\n' 或 '\u{1F600}'。
fn main() {
let c = 'q'
print("{c.is_alpha()} {c.to_upper()} {c.to_u32()} {'7'.to_digit(10)}")
}
true Q 113 Some(7)
Puddi 0.1 的大小写转换仅覆盖 ASCII。
集合
| 类型 | 构造方式 | 说明 |
|---|---|---|
List<T> | [1, 2, 3] | 可增长数组 |
Map<K, V> | ["a": 1, "b": 2],空映射写作 [:] | 键需要 Eq + Hash,按插入顺序迭代 |
Set<T> | Set.from([1, 2, 3]) | 元素需要 Eq + Hash,按插入顺序迭代 |
列表
fn main() {
let xs = [3, 1, 2]
xs.push(5)
print("{xs} has {xs.len()} items, first {xs[0]}")
print("{xs.get(10)} {xs.first()} {xs.pop()}")
xs[1] = 10
print("{xs.sorted()} {xs.contains(10)} {xs.index_of(2)}")
}
[3, 1, 2, 5] has 4 items, first 3
None Some(3) Some(5)
[2, 3, 10] true Some(2)
xs[i] 越界时触发陷阱,xs.get(i) 则返回 Option。
map、filter 等列表方法返回新列表:
fn main() {
let words = ["apple", "fig", "banana", "kiwi"]
let short = words.filter(|w| w.chars().count() <= 4)
let shout = short.map(|w| w.to_upper())
let total = words.fold(0, |acc, w| acc + w.chars().count())
print("{short} {shout} {total}")
print("{words.any(|w| w.starts_with("b"))} {words.find(|w| w.ends_with("i"))}")
print("{[1, 2, 3].sum()} {[4, 9, 2].max()}")
for (i, w) in words.enumerate() {
if i < 2 { print("{i}: {w}") }
}
}
["fig", "kiwi"] ["FIG", "KIWI"] 18
true Some("kiwi")
6 Some(9)
0: apple
1: fig
sort、sort_by 和 sort_by_key 原地排序。sorted 和 reversed 分别返回排序或反转后的副本。
映射
fn main() {
let ages = ["ada": 36, "alan": 41]
ages["grace"] = 85
ages.insert("ada", 37)
print("{ages["ada"]} {ages.get("bob")} {ages.get_or("bob", 0)}")
print("{ages.contains_key("alan")} {ages.len()}")
for (name, age) in ages {
print("{name} is {age}")
}
ages.remove("alan")
print("{ages.keys()}")
}
37 None 0
true 3
ada is 37
alan is 41
grace is 85
["ada", "grace"]
键不存在时,m[k] 会触发陷阱,m.get(k) 返回 Option。遍历映射会按插入顺序得到 (key, value) 元组。
集合
fn main() {
let a = Set.from([1, 2, 3])
let b = Set.from([2, 3, 4])
a.insert(3)
print("{a.len()} {a.contains(2)}")
print("{a.union(b).to_list()} {a.intersection(b).to_list()} {a.difference(b).to_list()}")
}
3 true
[1, 2, 3, 4] [2, 3] [1]
只读视图
通过集合自身的类型可以修改集合。如果函数只需读取,请用 ListView<T>、MapView<K, V> 或 SetView<T>。集合可隐式转成视图,视图仅提供读取方法。
fn count_long(words: ListView<Str>) -> Int {
words.filter(|w| w.chars().count() > 3).len()
}
fn main() {
let words = ["tea", "coffee", "water"]
print("{count_long(words)}")
}
2
区间与迭代器
a..b 是右端不包含的区间,a..=b 包含右端。区间、列表、映射和集合都能用于 for。.iter() 返回惰性迭代器,支持 map、filter、take、skip、zip、chain、enumerate、collect 等操作。
fn main() {
let squares = (1..=10).iter().map(|n| n * n).filter(|n| n % 2 == 0).take(3).to_list()
print("{squares}")
print("{(0..5).count()} {(0..5).contains(5)}")
}
[4, 16, 36]
5 false
控制流
if
if 是表达式。使用结果时,两条分支必须有相同类型。没有 else 时,if 的类型是 ()。
fn sign(x: Int) -> Int {
if x > 0 { 1 } else if x < 0 { -1 } else { 0 }
}
fn main() {
print("{sign(-4)} {sign(0)} {sign(9)}")
}
-1 0 1
match
match 从上至下匹配模式,必须覆盖所有可能的值。匹配分支写作 pattern -> expression。
fn label(code: Int) -> Str {
match code {
200 -> "ok"
404 -> "not found"
500..=599 -> "server error"
_ -> "other"
}
}
fn main() {
print("{label(200)} {label(503)} {label(302)}")
}
ok server error other
详见模式匹配。
循环
fn main() {
for i in 0..3 { print("for {i}") }
var n = 3
while n > 0 {
n -= 1
if n == 1 { continue }
print("while {n}")
}
let stack = [1, 2, 3]
while let Some(top) = stack.pop() {
print("popped {top}")
}
}
for 0
for 1
for 2
while 2
while 0
popped 3
popped 2
popped 1
for x in e 可以遍历任何实现了 Iterable 的值,包括区间、列表、映射、集合和迭代器。for 与 while 的类型都是 ()。
loop 重复运行直到 break。break 后面的值可作为整个 loop 的结果:
fn main() {
var x = 1
let first_big = loop {
x *= 3
if x > 100 { break x }
}
print("{first_big}")
}
243
条件里的结构体字面量
在 if、while、match 的条件或 for 的被遍历表达式中,给结构体字面量加括号,避免编译器把它的 { 当成主体代码块的起点。
struct Point { x: Int, y: Int }
fn main() {
let p = Point { x: 1, y: 2 }
if same(p, p) && (Point { x: 1, y: 2 }).x == p.x {
print("same x")
}
}
same x
提前退出
return 携带返回值离开函数。break 和 continue 可用于各种循环。它们与 panic 一样可出现在任意类型的分支中,因为执行到这里就不会继续求值。
fn first_negative(xs: List<Int>) -> Option<Int> {
for x in xs {
if x < 0 { return Some(x) }
}
None
}
fn main() {
print("{first_negative([3, -1, -5])} {first_negative([1])}")
}
Some(-1) None
函数与闭包
函数
顶层函数要写出参数和返回类型,省略返回类型时默认为 ()。函数体最后的表达式是返回值,也可以用 return 提前退出。
fn area(w: Int, h: Int) -> Int {
let s = w * h
s
}
fn report(name: Str, value: Int) {
print("{name}: {value}")
}
fn main() {
report("area", area(3, 4))
}
area: 12
方法
方法在 impl 块中声明,第一个参数是 self。没有 self 的是关联函数,通过类型名称调用。路径分隔符为 .。
struct Counter {
var count: Int
}
impl Counter {
fn new() -> Counter { Counter { count: 0 } }
fn bump(self, by: Int) { self.count += by }
fn get(self) -> Int { self.count }
}
fn main() {
let c = Counter.new()
c.bump(2)
c.bump(3)
print("{c.get()}")
}
5
值是引用,因此方法可直接修改对象中声明为 var 的字段,无需另写可变接收者。
闭包
闭包写作 |params| body。编译器通常可从使用位置推断参数类型。如果先保存闭包,再在别处使用,请给参数注明类型。
fn apply_twice(f: fn(Int) -> Int, x: Int) -> Int {
f(f(x))
}
fn main() {
let add = |a: Int, b: Int| -> Int { a + b }
print("{add(2, 3)}")
print("{apply_twice(|x| x * 10, 3)}")
print("{[1, 2, 3].map(|x| x + 1)}")
}
5
300
[2, 3, 4]
函数类型写作 fn(A, B) -> R。命名函数和闭包都能转换为这一类型。
fn double(x: Int) -> Int { x * 2 }
fn main() {
let ops: List<fn(Int) -> Int> = [double, |x: Int| x + 1]
for op in ops { print("{op(10)}") }
}
20
11
闭包按引用捕获变量。捕获 var 时,可以读到之后的赋值,也可以从闭包内部赋值。
fn main() {
var total = 0
let add = |x: Int| { total += x }
add(5)
add(7)
print("{total}")
}
12
泛型函数
类型参数写在尖括号中,约束跟在 : 后面。类型实参通常可在调用处推断,也可以显式写出。
fn largest<T: Ord>(xs: List<T>) -> Option<T> {
var best: Option<T> = None
for x in xs {
best = match best {
Some(b) if b >= x -> Some(b)
_ -> Some(x)
}
}
best
}
fn main() {
print("{largest([3, 9, 2])} {largest(["b", "a"])} {largest<Int>([])}")
}
Some(9) Some("b") None
约束的详细规则见特征与泛型。
结构体与枚举
结构体
@derive(Show)
struct Point {
x: Int
var y: Int
}
fn main() {
let p = Point { x: 1, y: 2 }
p.y = 5
let x = 10
let y = 20
let q = Point { x, y }
let r = Point { x: 7, ..p }
print("{p} {q} {r}")
}
Point { x: 1, y: 5 } Point { x: 10, y: 20 } Point { x: 7, y: 5 }
- 字段使用换行或逗号分隔
- 只有
var字段在对象构造之后还可重新赋值,其余字段对应 WasmGC 不可变字段 Point { x, y }是Point { x: x, y: y }的简写,..p从p读取其余字段- 字段默认仅在模块内可见,可用
pub公开
给未声明为 var 的字段重新赋值会导致编译错误。
struct Point {
x: Int
var y: Int
}
fn main() {
let p = Point { x: 1, y: 2 }
p.x = 5
}
结构体也可使用泛型。
struct Pair<A, B> { a: A, b: B }
fn main() {
let p = Pair { a: 1, b: "one" }
print("{p.a} {p.b}")
}
1 one
枚举
枚举是代数数据类型。变体可以不带值,也可带元组字段或具名字段。用 Shape.Circle 这样的路径引用变体。
enum Shape {
Circle(Float)
Rect { w: Float, h: Float }
Empty
}
fn area(s: Shape) -> Float {
match s {
Shape.Circle(r) -> 3.14 * r * r
Shape.Rect { w, h } -> w * h
Shape.Empty -> 0.0
}
}
fn main() {
let shapes = [Shape.Circle(1.0), Shape.Rect { w: 2.0, h: 3.0 }, Shape.Empty]
for s in shapes { print("{area(s)}") }
}
3.14
6.0
0.0
Option 和 Result 也是枚举。预导入项提供 Some、None、Ok、Err,所以它们可以不带路径使用。
元组和单元类型
元组将多个值组合而无需命名,例如 (Int, Str)。用 (1, "a") 构造,用 .0、.1 读取字段。单元类型 () 只有一个值,写作 ()。
fn min_max(xs: List<Int>) -> (Int, Int) {
(xs.min().unwrap(), xs.max().unwrap())
}
fn main() {
let t = min_max([4, 1, 7])
let (lo, hi) = t
print("{t.0} {t.1} {lo} {hi}")
}
1 7 1 7
派生特征
@derive 为内建特征生成实现,支持 Eq、Ord、Hash、Show 和 Transfer。
@derive(Eq, Ord, Hash, Show)
struct Version { major: Int, minor: Int }
fn main() {
let a = Version { major: 1, minor: 2 }
let b = Version { major: 1, minor: 10 }
print("{a < b} {a == b} {[b, a].sorted()}")
let seen = Set.from([a, b, a])
print("{seen.len()}")
}
true false [Version { major: 1, minor: 2 }, Version { major: 1, minor: 10 }]
2
Ord 按字段声明顺序比较。实现 Transfer 的值可发给工作线程。
类型别名
type UserId = Int
type Callback<T> = fn(T) -> ()
fn notify(id: UserId, cb: Callback<UserId>) { cb(id) }
fn main() {
notify(7, |id| print("user {id}"))
}
user 7
别名为原类型提供另一个名称,类型本身保持一致。
模式匹配
模式用于拆解值,可以写在 match、let、var、for、if let、while let 和 let ... else 中。
| 模式 | 示例 |
|---|---|
| 通配 | _ |
| 绑定 | x |
| 字面量 | 42、"hi"、'a'、true |
| 区间 | 1..=9、'a'..='z' |
| 元组 | (a, _, c) |
| 结构体 | Point { x, y: 0 }、Point { x, .. } |
| 枚举变体 | Some(v)、Shape.Rect { w, h } |
| 或模式 | A | B |
| 列表 | [first, ..rest]、[] |
match
enum Shape {
Circle(Float)
Rect { w: Float, h: Float }
Empty
}
fn describe(s: Shape) -> Str {
match s {
Shape.Circle(r) if r > 10.0 -> "big circle"
Shape.Circle(_) -> "circle"
Shape.Rect { w, h } if w == h -> "square {w}"
Shape.Rect { w, h } -> "rect {w}x{h}"
Shape.Empty -> "nothing"
}
}
fn main() {
print(describe(Shape.Circle(20.0)))
print(describe(Shape.Rect { w: 2.0, h: 2.0 }))
print(describe(Shape.Rect { w: 2.0, h: 3.0 }))
}
big circle
square 2.0
rect 2.0x3.0
分支可附加 if 守卫。编译器会检查穷尽性。如果有值无法匹配,诊断会举出未覆盖的取值。
enum Light { Red, Yellow, Green }
fn next(l: Light) -> Light {
match l {
Light.Red -> Light.Green
Light.Green -> Light.Yellow
}
}
fn main() {}
字面量 区间与或模式
fn kind(c: Char) -> Str {
match c {
'a' | 'e' | 'i' | 'o' | 'u' -> "vowel"
'a'..='z' -> "consonant"
'0'..='9' -> "digit"
_ -> "other"
}
}
fn main() {
print("{kind('e')} {kind('k')} {kind('4')} {kind('?')}")
}
vowel consonant digit other
列表
列表模式匹配长度,并可以用 ..name 绑定剩余部分。
fn summary(xs: List<Int>) -> Str {
match xs {
[] -> "empty"
[x] -> "just {x}"
[first, ..rest] -> "{first} and {rest.len()} more"
}
}
fn main() {
print(summary([]))
print(summary([5]))
print(summary([1, 2, 3]))
}
empty
just 5
1 and 2 more
解构绑定
struct Point { x: Int, y: Int }
fn main() {
let (a, b) = (1, "two")
let Point { x, .. } = Point { x: 3, y: 4 }
for (i, name) in ["ann", "bo"].enumerate() {
print("{i} {name}")
}
print("{a} {b} {x}")
}
0 ann
1 bo
1 two 3
if let、while let 与 let else
if let 在模式匹配时执行代码块。while let 在每一轮重新匹配。let ... else 绑定匹配结果,否则执行 else 块,该块必须用 return、break、continue 或 panic 离开当前控制流。
fn parse_pair(s: Str) -> Option<(Int, Int)> {
let Some((a, b)) = s.split_once(",") else {
return None
}
let Some(x) = a.trim().parse_int() else { return None }
let Some(y) = b.trim().parse_int() else { return None }
Some((x, y))
}
fn main() {
if let Some((x, y)) = parse_pair("3, 4") {
print("{x + y}")
}
print("{parse_pair("nope")}")
}
7
None
特征与泛型
特征
特征描述类型能够实现的一组方法。Puddi 使用名义特征,类型必须通过显式的 impl 块声明实现。
trait Shape {
fn area(self) -> Float
fn name(self) -> Str { "shape" }
}
struct Square { side: Float }
struct Circle { r: Float }
impl Shape for Square {
fn area(self) -> Float { self.side * self.side }
fn name(self) -> Str { "square" }
}
impl Shape for Circle {
fn area(self) -> Float { 3.0 * self.r * self.r }
}
fn main() {
let s = Square { side: 2.0 }
let c = Circle { r: 1.0 }
print("{s.name()} {s.area()}")
print("{c.name()} {c.area()}")
}
square 4.0
shape 3.0
特征中带方法体的是默认实现。impl 可以覆盖它。
类型约束
泛型函数通过类型约束说明所需能力,多个约束用 + 连接。
fn describe<T: Show + Eq>(a: T, b: T) -> Str {
if a == b { "{a} twice" } else { "{a} and {b}" }
}
fn main() {
print(describe(1, 1))
print(describe("x", "y"))
}
1 twice
x and y
泛型会单态化。编译器为每组实际类型生成对应的代码。
实现标准特征
Show 控制字符串插值时如何显示值。若 @derive(Show) 生成的行为不合适,可手写实现。
struct Money { cents: Int }
impl Show for Money {
fn show(self) -> Str {
let rest = self.cents % 100
let pad = if rest < 10 { "0" } else { "" }
"${self.cents / 100}.{pad}{rest}"
}
}
fn main() {
print("total: {Money { cents: 1205 }}")
}
total: $12.05
运算符对应的特征
实现对应特征后,就可以在该类型上使用运算符。
| 运算符 | 特征 |
|---|---|
+ - * / % | Add Sub Mul Div Rem |
一元 - ! | Neg Not |
== != | Eq |
< <= > >= | Ord |
a[i] | Index |
for x in a | Iterable |
"{a}" | Show |
@derive(Show)
struct V2 { x: Int, y: Int }
impl Add for V2 {
fn add(self, other: V2) -> V2 { V2 { x: self.x + other.x, y: self.y + other.y } }
}
fn main() {
print("{V2 { x: 1, y: 2 } + V2 { x: 10, y: 20 }}")
}
V2 { x: 11, y: 22 }
关联类型与父特征
特征可以声明关联类型,用 Self.Name 引用。也可以要求实现者同时实现其他特征。
trait Container {
type Item
fn items(self) -> List<Self.Item>
}
trait Named: Show {
fn title(self) -> Str { "<{self.show()}>" }
}
struct Bag { xs: List<Int> }
impl Container for Bag {
type Item = Int
fn items(self) -> List<Int> { self.xs }
}
impl Show for Bag {
fn show(self) -> Str { "bag of {self.xs.len()}" }
}
impl Named for Bag {}
fn main() {
let b = Bag { xs: [1, 2] }
print("{b.items()} {b.title()}")
}
[1, 2] <bag of 2>
泛型实现与一致性
impl 可以带类型参数及约束。
trait Describe {
fn describe(self) -> Str
}
impl<T: Show> Describe for List<T> {
fn describe(self) -> Str { "{self.len()} items: {self}" }
}
fn main() {
print([1, 2, 3].describe())
}
3 items: [1, 2, 3]
impl Trait for Type 须写在定义特征或定义类型的包中。对固定的类型和特征,最多有一个适用的实现。请留意已知差异。
特征对象
dyn Trait 可持有任意实现了该特征的值。运行时通过虚表分派调用,因此同一个列表可以容纳不同具体类型。
fn main() {
let items: List<dyn Show> = [1, "two", 3.5, [4]]
for it in items { print(it.show()) }
}
1
two
3.5
[4]
当上下文要求 dyn Trait 时,具体值可隐式转换。作为特征对象使用的方法不能有自己的类型参数,也不能在接收者之外使用 Self。关联类型必须确定,例如 dyn Iterator<Item = Int>。
错误处理
用 Option<T> 表示可能缺失的值,用 Result<T, E> 表示可失败的操作。无法恢复的程序错误用 panic 终止执行。
Option 与 Result
fn find_user(id: Int) -> Option<Str> {
if id == 1 { Some("ada") } else { None }
}
fn parse_port(s: Str) -> Result<Int, Str> {
match s.parse_int() {
Some(n) if n > 0 && n < 65536 -> Ok(n)
_ -> Err("bad port: {s}")
}
}
fn main() {
print("{find_user(1)} {find_user(2).unwrap_or("nobody")}")
print("{parse_port("8080")} {parse_port("x")}")
print("{parse_port("80").map(|p| p + 1)} {find_user(1).is_some()}")
}
Some("ada") nobody
Ok(8080) Err("bad port: x")
Ok(81) true
常用组合方法有 map、and_then、unwrap_or、unwrap_or_else、ok_or、map_err、is_some 和 is_ok。在 None 或 Err 上调用 unwrap 或 expect 会触发 panic。
问号运算符
后缀 ? 从 Some 或 Ok 中取出值,遇到 None 或 Err 时从当前函数提前返回。
fn add_strings(a: Str, b: Str) -> Option<Int> {
let x = a.parse_int()?
let y = b.parse_int()?
Some(x + y)
}
fn main() {
print("{add_strings("2", "3")} {add_strings("2", "z")}")
}
Some(5) None
对 Option 使用 ? 时,当前函数须返回 Option。对 Result 使用 ? 时,如果错误类型不同,可以通过 From 转换。
enum AppErr {
BadNumber(Str)
TooBig(Int)
}
impl Show for AppErr {
fn show(self) -> Str {
match self {
AppErr.BadNumber(s) -> "not a number: {s}"
AppErr.TooBig(n) -> "{n} is too big"
}
}
}
struct ParseErr { input: Str }
impl From<ParseErr> for AppErr {
fn from(e: ParseErr) -> AppErr { AppErr.BadNumber(e.input) }
}
fn parse(s: Str) -> Result<Int, ParseErr> {
s.parse_int().ok_or(ParseErr { input: s })
}
fn check(s: Str) -> Result<Int, AppErr> {
let n = parse(s)?
if n > 100 { return Err(AppErr.TooBig(n)) }
Ok(n)
}
fn main() {
for s in ["42", "abc", "500"] {
match check(s) {
Ok(n) -> print("ok {n}")
Err(e) -> print("error: {e}")
}
}
}
ok 42
error: not a number: abc
error: 500 is too big
Error 与 AnyErr
错误类型宜实现 Error,它要求 Show 并提供可选的 source 方法来表示错误链。AnyErr 可持有任何实现了 Error 的值。这类值可自动转成 AnyErr,让返回 Result<T, AnyErr> 的函数用 ? 传递这些错误。库可以提供明确的错误类型,应用则可用 AnyErr 简化转换。
import std.json
struct ConfigErr { msg: Str }
impl Show for ConfigErr {
fn show(self) -> Str { "config: {self.msg}" }
}
impl Error for ConfigErr {}
fn port(text: Str) -> Result<Int, AnyErr> {
let v = json.parse(text)?
let Some(p) = v.get("port").and_then(|p| p.as_int()) else {
return Err(AnyErr.new(ConfigErr { msg: "no port" }))
}
Ok(p)
}
fn main() {
print("{port("\{\"port\": 8080\}")}")
match port("\{\}") {
Ok(_) -> {}
Err(e) -> {
print("{e}")
if let Some(c) = e.downcast<ConfigErr>() { print("message: {c.msg}") }
}
}
match port("nonsense") {
Ok(_) -> {}
Err(e) -> print("{e}")
}
}
Ok(8080)
config: no port
message: no port
invalid JSON at byte 0: unexpected character
e.downcast<E>() 尝试取回原始错误,返回 Option<E>。
main 返回错误
当 E 实现 Show 时,main 可以返回 Result<(), E>。返回 Err 会输出错误,WASI 程序以失败状态退出,浏览器则把错误写入控制台。
Panic
panic(msg) 表示程序遇到无法恢复的错误。断言失败、整数溢出、除以零、索引越界或对 None、Err 解包也会触发 panic。它会使 WebAssembly 实例触发陷阱,Puddi 内部不可捕获。插件宿主会收到陷阱并继续运行,WASI 程序的退出状态是 101。
fn main() {
let xs = [1, 2, 3]
print("{xs[5]}") // traps: index out of bounds
}
程序缺陷适合用 panic,调用方能够处理的失败适合用 Result。
模块
每个文件是一个模块。模块路径与 src/ 下的文件路径对应。
| 文件 | 模块 |
|---|---|
src/main.pud | 程序根模块 |
src/lib.pud | 库根模块 |
src/parser.pud | parser |
src/net/http.pud | net.http |
导入
import net.http // use as http.get(...)
import net.http.{get, Request} // import specific names
import net.http as h // alias
import json // a dependency named in pud.toml
import std.fs // a standard library module
import wasi:clocks/system-clock // a WIT interface, see Host interop
导入后可用模块路径最后一段或别名访问它,例如 http.get。同一个包内的模块可以循环导入,包之间的依赖不能成环。
可见性
声明和结构体字段默认只在所属模块内可见。标为 pub 后,其他模块和包可访问。
// src/account.pud
pub struct Account {
pub owner: Str
var balance: Int // private: only this module can read or set it
}
impl Account {
pub fn open(owner: Str) -> Account { Account { owner, balance: 0 } }
pub fn deposit(self, amount: Int) { self.balance += amount }
pub fn balance(self) -> Int { self.balance }
}
// src/main.pud
import account.{Account}
fn main() {
let a = Account.open("ada")
a.deposit(10)
print("{a.owner} has {a.balance()}")
// a.balance = 99 would not compile: the field is private
}
export 把函数公开为编译后组件的导出,规则见插件。
特定目标的代码
@target 只在构建指定目标时保留该声明。
@target(wasi)
fn home() -> Str { "terminal" }
@target(browser, plugin)
fn home() -> Str { "embedded" }
标准库
std 模块使用同样的导入语法。导入当前目标不提供的模块会导致编译错误。详见各目标可用的模块。
测试
test 块可以写在任何源文件中,与被测代码放在一起。pud test 才会编译测试,并为每个测试启动一个新实例,避免测试共享状态。
fn fizz(n: Int) -> Str {
match (n % 3, n % 5) {
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
_ -> "{n}"
}
}
test "multiples of three" {
assert_eq(fizz(9), "Fizz")
}
test "multiples of both" {
assert_eq(fizz(30), "FizzBuzz")
assert(fizz(7) == "7")
}
pud test # all tests in the package
pud test fizz.pud # tests in one file
pud test . "multiples" # tests in the package whose name contains "multiples"
发生 panic 时测试失败,包括 assert、assert_eq、assert_ne 或 assert_msg 失败。assert_eq 比较失败时会输出两个值。
异步测试
测试体可直接使用 .await。
import std.time
async fn slow_double(x: Int) -> Int {
time.sleep(1).await
x * 2
}
test "async code" {
assert_eq(slow_double(21).await, 42)
}
测试宿主
pud test 在 JavaScript 宿主中运行,需要 Node.js 22 或更新版本。运行异步测试还需要 JSPI,Node.js 24 默认启用它。测试无法调用 WIT 导入,相关代码可以放到可替换的函数后面,或另用 pud run 执行小型集成程序。
异步与任务
异步函数
用 async fn 编写需要等待计时器、网络或另一个任务的代码,用后缀 .await 等待结果。异步函数、异步闭包和测试体可以使用 .await,入口 main 也可以声明为异步函数。
import std.time
async fn slow_square(x: Int) -> Int {
time.sleep(10).await
x * x
}
async fn main() {
let a = slow_square(3).await
let b = slow_square(4).await
print("{a + b}")
}
25
.await 与方法调用的绑定强度相同。fetch(url).await? 先等待结果,再用 ? 传播错误。
结构化并发
并发任务在任务作用域内启动。task.scope 接收一个异步闭包,并将作用域作为参数传入。s.spawn(future) 启动子任务并返回可等待的句柄。作用域会等所有子任务结束后才退出,因此任务不会超出启动它的代码范围。
import std.time
async fn job(name: Str, ms: Int) -> Str {
time.sleep(ms).await
print("{name} done")
name
}
async fn main() {
let names = task.scope(async |s| {
let slow = s.spawn(job("slow", 200))
let fast = s.spawn(job("fast", 10))
[slow.await, fast.await]
}).await
print("{names}")
}
fast done
slow done
["slow", "fast"]
两个任务同时等待,后启动的短任务先结束。
取消
子任务失败,或作用域主体通过 return、错误上的 ? 等方式提前退出时,其余任务会被取消。取消是协作式的,任务到达下一处 .await 时停止。长时间执行的同步循环可主动检查 task.is_cancelled()。
import std.time
async fn step(n: Int) -> Result<Int, Str> {
time.sleep(n * 50).await
if n == 2 { return Err("step {n} failed") }
print("step {n} ok")
Ok(n)
}
async fn run() -> Result<Int, Str> {
task.scope(async |s| {
let a = s.spawn(step(1))
let b = s.spawn(step(2))
let c = s.spawn(step(5))
Ok(a.await? + b.await? + c.await?)
}).await
}
async fn main() {
print("{run().await}")
}
step 1 ok
Err("step 2 failed")
b.await? 把错误返回给作用域时,正在休眠的 step(5) 被取消,因此不输出。
异步闭包与方法
闭包可以是异步的,例如 async |url| { fetch(url).await }。特征方法也可以声明为 async fn,包括通过 dyn Trait 调用的方法。异步函数值的类型写作 async fn(Int) -> Str。
宿主调度
在 wasi 上,每个子任务运行于自己的组件模型线程,阻塞的 WASI 调用只挂起当前任务。浏览器、Node.js 和 pud test 的 JavaScript 宿主用 JSPI 调度。同一个实例里的任务共享堆,但不同时执行 Puddi 代码。需要并行计算时请使用工作线程。
工作线程
WasmGC 对象无法在线程间共享,因此 Puddi 用隔离的工作线程做并行计算。每个工作线程是一个独立 WebAssembly 实例,拥有自己的堆,并通过消息与父实例通信。
import std.worker
@derive(Transfer)
struct Job {
id: Int
data: List<Int>
}
async fn summer(port: worker.Port<Job, Int>) {
while let Some(job) = port.recv().await {
port.send(job.data.sum())
}
}
async fn main() {
task.scope(async |s| {
let w = s.worker(summer)
w.send(Job { id: 1, data: [1, 2, 3] })
w.send(Job { id: 2, data: [10, 20] })
print("{w.recv().await} {w.recv().await}")
}).await
}
Some(6) Some(30)
- 在任务作用域内用
s.worker(f)启动工作线程,作用域结束时它会终止 f必须是顶层异步函数,不能使用捕获环境的闭包。它接收worker.Port<In, Out>,读取In并发送Outs.worker(f)返回通道的另一端,发送In并读取Out。当另一端已退出,recv()返回None
Transfer
消息在实例间深拷贝,因此消息类型必须实现 Transfer。数值、Bool、Char、Str 以及由 Transfer 类型组成的元组、Option、Result 和集合均可传输。当结构体和枚举的字段都可传输时,可用 @derive(Transfer) 派生。函数、闭包和 dyn 值不能传输。
宿主支持
| 目标 | 运行方式 |
|---|---|
browser | Web Workers,Node.js 中使用工作线程 |
wasi | 通过 puddi:runtime 接口在其他操作系统线程启动组件实例 |
plugin | 宿主 world 导入 puddi:runtime 工作线程接口时可用 |
pud run 的内嵌运行时提供 puddi:runtime 接口。其他 WASI 宿主需要自行提供才能运行使用工作线程的程序。详见构建目标。
pud 命令
Puddi 的工具链统一通过 pud 访问。
| 命令 | 用途 |
|---|---|
pud new <name> | 创建包 |
pud build [path] [--target t] [--emit-wat] [-o dir] | 构建组件,默认目标是 wasi |
pud run [path|file.pud] [-- args] | 构建后运行 |
pud test [path|file.pud] [filter] | 运行测试块 |
pud check [path|file.pud] | 检查类型,不生成代码 |
pud fmt [files] [--check] | 按官方风格格式化源码 |
pud doc [path] | 为公开声明生成 Markdown |
pud add <repo@version|path> [--name n] | 添加依赖 |
pud version | 输出版本 |
build、run、test、check、doc 可接受包目录、pud.toml 或单个源文件的路径。省略路径时从当前目录向上查找清单。把源文件作为包的一部分处理时,请传入包路径。
单文件模式
.pud 文件可脱离包检查、运行和测试,也可导入标准库及工具链提供的 WIT 接口。单文件不能使用包依赖。
pud run script.pud -- input.txt
构建
默认在 target/<target>/<name>.wasm 生成 WebAssembly 组件。
- 用
--target或-t选择wasi、browser、plugin。见构建目标 --emit-wat另存核心模块的 WebAssembly 文本-o dir或--out dir指定输出目录
运行
| 目标 | pud run 的行为 |
|---|---|
wasi | 用内嵌 Wasmtime 运行 main,将 -- 后的参数传给程序 |
browser | 在回环地址启动开发服务器,并输出访问 URL |
plugin | 用 pud run --target plugin -- <export> [args] 调用一个导出并输出结果 |
PUD_HOST=node pud run 用 Node.js 和 JavaScript 宿主函数运行 wasi 的核心模块。
测试
Node.js 为每个测试创建一个新实例。路径参数之后可跟一个筛选词,只运行名字包含该词的测试。
pud test . parser
格式化
pud fmt 使用固定风格。加上 --check 只检查,不修改文件;有文件需格式化时返回状态码 1。传入 .pud 文件可限定范围。
生成文档
pud doc 从公开声明收集 /// 注释。包的文档输出到 target/doc/<name>.md,单文件模式则在当前目录生成 <name>.md。
/// Splits a line into words, dropping empty ones.
pub fn words(line: Str) -> List<Str> { line.split_whitespace() }
添加依赖
pud add github.com/someone/lib@1.2 # a git dependency
pud add ../shared --name shared # a local path dependency
命令修改 pud.toml 的 [deps] 并更新 pud.lock。详见依赖。
环境变量
| 变量 | 效果 |
|---|---|
PUD_HOST=node | 用 Node.js 的 JavaScript 宿主运行 wasi 核心模块 |
PUD_PORT | 浏览器开发服务器的起始端口,默认为 8000 |
主分支新增选项见编译器开发。
包清单
pud.toml 位于包的根目录。
[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"
[deps]
json = "github.com/someone/puddi-json@1.2"
util = { path = "../util" }
[target.wasi]
world = "wasi:cli/command"
[target.plugin]
world = "wit/host.wit#plugin"
package
| 键 | 含义 |
|---|---|
name | 包名,用于构建产物和依赖引用 |
version | 包版本,遵循语义化版本格式 |
puddi | 该包使用的语言版本 |
deps
每项定义一个依赖及其来源。可以引用 Git 仓库及最低版本,也可以引用本地路径。键名用于 import。见依赖。
target wasi
[target.wasi] 的 world 指定组件的 WIT world,缺省值为 wasi:cli/command。
target plugin
[target.plugin] 必须设置 world,格式为相对包目录的 <file>#<world>,例如 wit/host.wit#plugin。
包目录结构
my-package/
├── pud.toml
├── pud.lock # written by pud; commit it
├── src/
│ ├── main.pud # or lib.pud for a library
│ └── ...
├── wit/ # WIT files of your own, if any
└── target/ # build output; do not commit
包内 wit/ 下的接口可以和工具链自带的 WASI 及 puddi:runtime 接口一同导入。见 WIT 导入。
依赖
包依赖可以是发布语义化版本标签的 Git 仓库,也可以是本地目录。
[deps]
json = "github.com/someone/puddi-json@1.2"
util = { path = "../util" }
依赖键名(如 json、util)用于导入。import json 导入其根模块,import json.parser 导入子模块。仅 pub 声明对其他包可见。
Git 依赖
@ 后是最低版本,仓库用 v1.2.0 等 Git 标签发布。pud add 写入清单并解析依赖。
pud add github.com/someone/puddi-json@1.2
最小版本选择
每个依赖选择满足整张依赖图所有要求的最低版本。因此构建不会自动使用高于要求的发行版。一个包的不同主版本是不同的依赖,可同时使用。
锁文件
pud.lock 记录解析出的标签对应的确切提交,避免标签被移动后悄悄改变构建结果。将它与 pud.toml 一起提交。
路径依赖
[deps]
util = { path = "../util" }
路径相对于清单所在目录。单仓库管理多个包,或同时开发库和应用时,可用路径依赖。
规则
- 包之间的依赖必须无环,同一包内的模块可以循环导入
- 单文件模式如
pud run file.pud无法使用包依赖 impl Trait for Type须放在定义该特征或类型的包中
构建目标
各目标使用同一套语言。@target(...) 可把声明限定到特定目标。导入目标不支持的模块会导致编译错误,见各目标可用的模块。
| 目标 | 产物 | 入口 |
|---|---|---|
wasi,默认 | 对应 [target.wasi] world 的 WASI 0.3 组件,默认 wasi:cli/command | 命令使用 fn main() 或 async fn main(),其他 world 使用 export fn |
browser | 组件与 JavaScript 加载器 puddi.mjs | fn main()、async fn main()、export fn |
plugin | 对应 [target.plugin] world 的组件 | world 所要求的导出 |
wasi
缺省目标 world 是 wasi:cli/command@0.3.2,也可通过 [target.wasi] 选择其他 world。运行时使用 WASI 流读写标准输入和输出,通过文件系统预打开目录访问文件,通过 wasi:clocks、wasi:random 获取时间与随机数,std.http 走 wasi:http/client。run 使用异步 ABI,阻塞 WASI 调用只挂起发出调用的任务。
WASI 产物要求 WASI 0.3。pud run 使用内嵌 Wasmtime。外部宿主还须支持组件模型的异步和线程、WasmGC 和异常处理。使用工作线程时,还须提供 puddi:runtime 接口。
使用 --no-default-features 构建的 pud 省去了内嵌运行时。可以执行 pud build 后将组件交给兼容宿主。如果程序可以使用 JavaScript 宿主函数,也可用 PUD_HOST=node pud run。
browser
pud build --target browser 生成组件和 puddi.mjs。pud run --target browser 启动本地开发服务器。加载器从组件中取出核心模块,再以 JavaScript 宿主函数实例化。浏览器需要 WasmGC,异步代码还需要 JSPI。见浏览器。
plugin
插件根据编辑器、游戏或服务等宿主定义的 WIT world 构建。清单指定 world:
[target.plugin]
world = "wit/host.wit#plugin"
export fn 实现 world 的导出。编译器会检查必需导出及其签名。见插件。
输出格式
各目标都使用 WasmGC。结构体和枚举会映射到 GC 结构体,泛型会单态化,闭包和特征对象在 GC 结构体中保存函数引用。组件由 wit-component 编码。
故障排查
安装与查找包
- 找不到
pud:安装后重新打开终端。默认安装请确认~/.pud/bin在PATH中,再运行pud version could not find pud.toml:进入包目录或显式传入路径。单文件模式应传入实际存在的.pud文件,不会加载同目录模块或包的依赖- 无法解析 Git 依赖:检查仓库地址、Git 是否可用、远端是否发布了符合要求的语义化版本标签。将
pud.lock和pud.toml一起提交。见依赖
宿主与目标
| 现象 | 排查方向 |
|---|---|
pud test 无法启动 Node.js | 在同一终端运行 node --version,需要 Node.js 22 或更新版本 |
| 异步示例提示缺少 JSPI | 用 Node.js 24 跑测试,或在支持 JSPI 的浏览器中运行 |
找不到 std.dom | 用 --target browser 检查或构建 |
找不到 std.fs、std.io、std.env | 选择 wasi 目标 |
| 浏览器无法加载 Wasm 文件 | 打开 pud run --target browser 输出的网址,或用 HTTP 一并提供所有产物 |
| 外部运行时拒绝加载组件 | 检查 WasmGC、异常、WASI 0.3 及组件模型异步和线程支持 |
| 插件导出签名不匹配 | 对照 WIT 类型映射检查类型 |
| 调用插件导入时触发陷阱 | 使用提供该 WIT 接口的宿主 |
报告问题
请附上 pud version、操作系统、命令、目标、完整诊断和可复现的最小程序。涉及 WIT 时也请附上清单中的 world 和相关声明。可先查已知差异,再报告问题或在讨论区提问。
WIT 导入
组件模型使用 WIT 描述宿主接口。按 WIT 名称导入接口时,Puddi 会为其生成有类型的绑定,并把接口加入组件的 world。
import wasi:clocks/system-clock as clock
fn main() {
let now = clock.now()
print("{now.seconds > 0}")
}
true
pud 自带 WASI 0.3 接口,包括 wasi:cli、wasi:clocks、wasi:filesystem、wasi:http、wasi:logging、wasi:random、wasi:sockets 和 puddi:runtime。包的 wit/ 目录也可以提供 WIT 文件。
类型映射
| WIT | Puddi |
|---|---|
bool | Bool |
s8 s16 s32 s64 | I8 I16 I32 I64 |
u8 u16 u32 u64 | U8 U16 U32 U64 |
f32 f64 | F32 F64 |
char | Char |
string | Str |
list<T> | List<T> |
option<T> | Option<T> |
result<T, E> | Result<T, E> |
tuple<...> | 元组 |
record | struct |
variant、enum | enum |
flags | 编译器生成由 Bool 字段组成的结构体 |
resource | 具有方法和 drop() 的句柄结构体 |
名称按 Puddi 约定转换。WIT 记录 entry 变成结构体 Entry,枚举成员 info 变成变体 Level.Info,函数和字段用 snake_case。通过导入名访问这些类型,如 log.Entry。
绑定生成
编译器把绑定生成成 Puddi 代码,负责按规范 ABI 接收和传递值,并与程序一起编译。pud check 能像检查普通调用一样检查 WIT 调用。
导出与限制
export fn 声明组件导出。在 plugin 上,导出要与宿主 world 一致。wasi:cli/command 以外的 WASI world 也用此方式实现。
v0.1.2 支持在 WIT 导出中使用接口声明的记录、变体、枚举和标志位。pud test 的 JavaScript 宿主不支持调用 WIT 导入。pud run 的插件支持范围见宿主能力。
插件
plugin 目标根据宿主应用定义的 WIT world 构建。World 描述插件可以调用的导入,以及必须实现的导出。
从 WIT 到运行
宿主先公布 WIT world:
// wit/host.wit
package demo:host;
interface log {
enum level { info, warn }
record entry { level: level, message: string }
write: func(e: entry);
}
world plugin {
import log;
export greet: func(name: string, times: u32) -> list<string>;
export classify: func(n: s64) -> result<string, option<u8>>;
}
插件清单引用 world:
[package]
name = "greeter"
version = "0.1.0"
puddi = "0.1"
[target.plugin]
world = "wit/host.wit#plugin"
每个导出由 export fn 实现:
// src/main.pud
import demo:host/log
export fn greet(name: Str, times: U32) -> List<Str> {
log.write(log.Entry { level: log.Level.Info, message: "greeting {name}" })
let out: List<Str> = []
for i in 0..times.to_int().unwrap_or(0) {
out.push("hi {name} {i}")
}
out
}
export fn classify(n: I64) -> Result<Str, Option<U8>> {
if n > 0 { Ok("positive {n}") } else if n == 0 { Err(None) } else { Err(Some(7)) }
}
pud build --target plugin # target/plugin/greeter.wasm
pud run --target plugin -- classify 5
ok("positive 5")
缺少导出或函数签名与 world 不一致时会报编译错误。异步 WIT async func 应用 export async fn 实现,可以在其中创建任务并等待结果。
宿主能力
插件可以使用其 world 所提供的标准模块。
| 模块 | world 需要导入的接口 |
|---|---|
std.time | wasi:clocks/monotonic-clock、wasi:clocks/system-clock |
std.random | wasi:random/random |
std.http | wasi:http/types、wasi:http/client |
std.worker | puddi:runtime/workers、puddi:runtime/port |
std.log、print | wasi:logging/logging,没有该接口时不输出日志 |
pud run --target plugin -- <export> [args] 通过内嵌运行时调用一个导出。内嵌运行时实现上表的能力。调用 demo:host/log 等自定义接口时,需要提供该接口的实际宿主。
插件中的 panic
Panic 使插件实例触发陷阱。宿主会收到调用错误,可继续运行。
浏览器
browser 目标生成组件和加载器 puddi.mjs。std.dom 用于操作文档,std.http 由 fetch 实现,std.worker 使用 Web Workers。
import std.dom
fn main() {
dom.set_title("Counter")
let label = dom.create("p")
label.set_text("clicked 0 times")
let button = dom.create("button")
button.set_text("click me")
var clicks = 0
button.on("click", |e| {
clicks += 1
label.set_text("clicked {clicks} times")
})
dom.body().append(label)
dom.body().append(button)
}
pud run --target browser # serves the page on http://127.0.0.1:8000
pud build --target browser # writes target/browser/<name>.wasm and puddi.mjs
部署
pud build --target browser 将 <name>.wasm、puddi.mjs 和 index.html 写入 target/browser/。把它们放到同一个静态站点目录,.wasm 文件用 application/wasm 类型提供。
也可以在自定义网页里以模块形式加载 Puddi 程序。
<script type="module">
import { load } from "./puddi.mjs";
const app = await load("./counter.wasm", {
output(fd, line) { (fd === 2 ? console.error : console.log)(line) }
});
await app.run(); // runs main and resolves to the exit code
</script>
load 返回 { instance, exports, run }。回调 output 接收输出的每一行,fd 为 1 表示标准输出,为 2 表示错误或 panic。省略回调时,输出发往控制台。
浏览器要求
浏览器需要支持 WebAssembly GC。异步代码还要求 JSPI。可以用近期的 Chromium 浏览器运行异步示例,或检查环境中是否存在 WebAssembly.Suspending 与 WebAssembly.promising。
加载器原理
加载器的作用类似 jco transpile,它从组件中取出核心模块,提供该组件所需的 JavaScript 宿主函数,然后实例化核心模块。
DOM API 见 std.dom。
核心 WebAssembly 互操作
组件模型是主要的宿主互操作方式。若宿主只支持核心 WebAssembly,可用 @extern 和 @export 声明原始导入和导出。
@extern("env", "log")
fn log(msg: Str)
@export("run")
fn run() { log("hi") }
@extern(module, name)声明无函数体的核心导入,宿主以module.name提供实现@export(name)将函数以指定名称导出到核心模块- 只有数值类型与
Str可直接跨越该边界,其余类型需自行编解码
支持组件的宿主适合使用 WIT 导入和 export fn,这样编译器可以检查完整类型。
预导入项
每个模块无需 import 就可以使用下列名称。
| 类别 | 名称 |
|---|---|
| 类型 | Bool、Int、Float 及各位宽的数值类型、Char、Str、StrBuilder、List、Map、Set、ListView、MapView、SetView、Option、Result、AnyErr |
| 变体 | Some、None、Ok、Err |
| 特征 | Eq、Ord、Hash、Show、From、Error、Transfer、Add、Sub、Mul、Div、Rem、Neg、Not、Index、Iterable、Iterator |
| 函数 | print、eprint、panic、assert、assert_msg、assert_eq、assert_ne、same、min、max、todo |
| 值 | task,用于任务作用域 |
预导入项使用 Puddi 编写,参见实现源码。
函数
| 函数 | 含义 |
|---|---|
print(x) | 输出值与换行,WASI 用标准输出,浏览器用控制台,插件用日志 |
eprint(x) | 将同样的内容写到标准错误流 |
panic(msg) | 报告无法恢复的错误并停止执行 |
assert(cond)、assert_msg(cond, msg) | 条件为假时 panic |
assert_eq(a, b)、assert_ne(a, b) | 不满足相等或不等要求时打印两值并 panic |
same(a, b) | 两个引用是否指向同一对象 |
min(a, b)、max(a, b) | 取两个 Ord 值中较小或较大的一个 |
todo() | 以 not yet implemented 为消息触发 panic,可用在任何类型的位置 |
常用类型的方法
以下清单可用于查找方法名。用法见语言指南。
Option<T>: is_some is_none unwrap expect unwrap_or unwrap_or_else map and_then or or_else filter ok_or ok_or_else to_list
Result<T, E>: is_ok is_err ok err unwrap unwrap_err expect unwrap_or unwrap_or_else map map_err and_then
Str: utf8_len is_empty chars graphemes start end find rfind contains starts_with ends_with slice slice_from slice_to next_index advance split_once split split_whitespace lines trim trim_start trim_end to_upper to_lower replace repeat parse_int parse_i64 parse_float to_bytes, 以及 Str.from_chars、Str.from_utf8
Char: to_u32 is_digit is_alpha is_alphanumeric is_whitespace is_upper is_lower is_ascii to_upper to_lower to_digit to_str, 以及 Char.from_u32
StrBuilder: new reserve push push_char push_byte len to_str
List<T>: new with_capacity filled len is_empty push pop get set first last insert remove clear truncate swap extend concat copy slice take skip view enumerate map filter flat_map filter_map for_each fold any all count find position zip reverse reversed sort sort_by sort_by_key sorted contains index_of min max dedup; List<Str> 还有 join,Int、I64、Float 的列表还有 sum
Map<K, V>: new len is_empty insert get get_or contains_key remove clear keys values entries view
Set<T>: new from len is_empty insert contains remove clear to_list union intersection difference view
视图 (ListView, MapView, SetView): 对应集合的读取方法
区间 (a..b, a..=b): start end contains to_list map filter for_each fold any all count rev
Iterator: next map filter enumerate take skip zip chain collect to_list count fold for_each any all find position last min max
AnyErr: AnyErr.new(e) msg downcast inner
数值: wrapping_*、saturating_*、checked_* 算术方法,to_<type>() 窄化转换,truncate_to_int、round_to_int 等。浮点数还支持 sqrt cbrt pow exp ln log2 log10 sin cos tan asin acos atan atan2 hypot floor ceil round abs. 见数值。
各目标可用的模块
标准模块用 import std.<name> 导入。模块须由当前构建目标提供。
| 模块 | 用途 | browser | wasi | plugin |
|---|---|---|---|---|
std.json | JSON 值、解析与序列化 | 是 | 是 | 是 |
std.log | 分级日志 | 是 | 是 | 是 |
std.math | 数学常量和函数 | 是 | 是 | 是 |
std.bytes | 字节序转换和有边界检查的二进制读取 | 是 | 是 | 是 |
std.collections | 双端队列、优先队列、分组和计数 | 是 | 是 | 是 |
std.csv | 按 CSV 引号规则处理分隔文本 | 是 | 是 | 是 |
std.date | 公历日期、UTC 时间戳和 Unix 时间转换 | 是 | 是 | 是 |
std.encoding | 十六进制、Base64、Base64url 和百分号编码 | 是 | 是 | 是 |
std.fmt | 值格式化和整数进制转换 | 是 | 是 | 是 |
std.iter | 惰性迭代器来源 | 是 | 是 | 是 |
std.path | 以斜杠分隔的路径文本操作 | 是 | 是 | 是 |
std.stats | 统计摘要、方差、标准差和中位数 | 是 | 是 | 是 |
std.text | 按 Unicode 标量截断和填充,移除前后缀 | 是 | 是 | 是 |
std.time | 时钟和休眠 | 是 | 是 | 依赖宿主 |
std.random | 随机数 | 是 | 是 | 依赖宿主 |
std.http | HTTP 客户端 | 是 | 是 | 依赖宿主 |
std.worker | 并行工作线程 | 是 | 依赖宿主 | 依赖宿主 |
std.io | 标准输入与输出 | — | 是 | — |
std.fs | 文件和目录 | — | 是 | — |
std.env | 参数、环境变量和退出 | — | 是 | — |
std.dom | 浏览器文档 | 是 | — | — |
“依赖宿主”表示目标 world 须包含相应接口。在 wasi 上,std.worker 使用内嵌运行时提供的 puddi:runtime 接口。插件的 std.log 在 world 包含日志接口时写入宿主,否则不输出。
详见便携模块 API 参考和标准库源码。
std.json
提供 JSON 值、解析与序列化,在所有目标上可用。
import std.json
import std.json.{Json}
fn main() {
let v = json.parse("\{\"name\": \"ada\", \"langs\": [\"en\", \"fr\"], \"age\": 36\}").unwrap()
print("{v.get("name").and_then(|n| n.as_str())}")
print("{v.get("langs").and_then(|l| l.at(1))}")
print("{v.get("age").and_then(|a| a.as_int())} {v.get("missing").is_none()}")
let out = Json.Object(["ok": Json.Bool(true), "items": Json.Array([Json.Number(1.0), Json.Null])])
print(json.stringify(out))
}
Some("ada")
Some("fr")
Some(36) true
{"ok":true,"items":[1,null]}
Json
pub enum Json {
Null
Bool(Bool)
Number(Float)
String(Str)
Array(List<Json>)
Object(Map<Str, Json>)
}
对象按插入顺序保存键。Json 的显示格式也是 JSON 文本,因此 "{v}"、print(v) 的结果与 stringify(v) 一致。
| 方法 | 返回值 |
|---|---|
get(key) | 对象成员,缺失时为 None |
at(i) | 数组元素,缺失时为 None |
is_null() | 值是否为 null |
as_bool()、as_float()、as_int()、as_str() | 尝试按指定类型读取;as_int 要求值为范围内整数 |
as_list()、as_map() | 数组的元素或对象的成员 |
函数
| 函数 | 含义 |
|---|---|
parse(text) -> Result<Json, ParseErr> | 解析 JSON,decode 是同一接口 |
stringify(v) -> Str | 输出紧凑 JSON 文本,encode 是同一接口 |
ParseErr 公开 msg 和表示字节偏移的 pos,并实现 Show 和 Error。可通过 ? 转成 AnyErr。
std.http
异步 HTTP 客户端。浏览器目标通过 fetch 发送请求,WASI 目标通过 WASI HTTP,插件目标需要宿主提供 HTTP 接口。
import std.http
async fn main() -> Result<(), http.HttpErr> {
let res = http.get("https://example.com/").await?
print("{res.status} {res.ok()} {res.header("content-type")}")
let body = res.text().await?
print("{body.utf8_len()} bytes")
Ok(())
}
请求
import std.http
async fn main() -> Result<(), http.HttpErr> {
let res = http.Request.new("PUT", "https://example.com/items/1")
.header("content-type", "application/json")
.with_body("\{\"done\": true\}")
.send()
.await?
print("{res.status}")
Ok(())
}
| 函数或方法 | 含义 |
|---|---|
get(url)、post(url, body) | 发送请求,返回 Result<Response, HttpErr> |
request(req) | 发送 Request |
Request.new(method, url) | 创建正文为空且没有请求头的请求 |
req.header(name, value) | 返回添加了请求头的副本 |
req.with_body(body) | 返回带新正文的副本 |
req.send() | 发送请求 |
发送操作均为异步函数,需要等待结果。
响应
Response 公开了 status: Int 和 headers: List<(Str, Str)>。用 text() 或 json() 读取正文。
| 方法 | 含义 |
|---|---|
ok() | 状态码是否在 200–299 之间 |
header(name) | 忽略大小写,返回第一个同名响应头 |
text() | 将正文读取为字符串 |
json() | 把正文解析为 Json |
错误
HttpErr 实现了 Show 和 Error。
| 变体 | 含义 |
|---|---|
HttpErr.Network(msg) | 无法发送请求或没有收到响应 |
HttpErr.InvalidUrl(msg) | 无法解析 URL |
HttpErr.Body(msg) | 正文不符合所需格式,例如 json() 遇到无效 JSON |
std.io、std.fs 和 std.env
标准流、文件系统、命令行参数和环境变量仅由 wasi 目标提供。
std.io
| 函数 | 含义 |
|---|---|
read_line() -> Option<Str> | 读取一行,去掉行尾;输入结束时返回 None |
read_all() -> Str | 读取剩余的全部标准输入 |
write(s) | 写到标准输出,无额外换行 |
ewrite(s) | 写到标准错误流,无额外换行 |
import std.io
fn main() {
var lines = 0
var words = 0
while let Some(line) = io.read_line() {
lines += 1
words += line.split_whitespace().len()
}
io.write("{lines} lines, {words} words\n")
}
std.fs
路径在宿主开放的目录中解析。内嵌的 pud run 以读写权限开放当前工作目录和 /,并继承调用进程环境。运行不熟悉的程序时,可使用只开放所需目录和环境变量的宿主。
| 函数 | 含义 |
|---|---|
read(path) -> Result<Str, IoErr> | 将整个文件读取为字符串 |
write(path, content) -> Result<(), IoErr> | 创建或替换文件 |
append(path, content) -> Result<(), IoErr> | 追加内容,文件不存在时创建 |
exists(path) -> Bool | 路径是否存在 |
is_dir(path) -> Bool | 是否为目录 |
remove(path) -> Result<(), IoErr> | 删除文件或空目录 |
list_dir(path) -> Result<List<Str>, IoErr> | 列出目录中的名称 |
create_dir(path) -> Result<(), IoErr> | 创建目录 |
import std.fs
fn main() -> Result<(), AnyErr> {
fs.write("notes.txt", "first\n")?
fs.append("notes.txt", "second\n")?
let text = fs.read("notes.txt")?
print("{text.lines()}")
fs.remove("notes.txt")?
print("{fs.exists("notes.txt")}")
match fs.read("missing.txt") {
Ok(_) -> print("found it")
Err(fs.IoErr.NotFound(_)) -> print("missing.txt does not exist")
Err(e) -> print("{e}")
}
Ok(())
}
["first", "second"]
false
missing.txt does not exist
IoErr 实现 Show 和 Error,有 NotFound、PermissionDenied、AlreadyExists、Other 四种变体,各带一条消息。
std.env
| 函数 | 含义 |
|---|---|
args() -> List<Str> | 命令行参数,第一项是程序名 |
get(name) -> Option<Str> | 读取环境变量 |
exit(code) | 立即以指定状态码退出 |
import std.env
fn main() {
let args = env.args()
if args.len() < 2 {
print("usage: {args[0]} <file>")
env.exit(2)
}
print("home is {env.get("HOME").unwrap_or("unknown")}")
}
std.time 与 std.random
两者都适用于 browser 和 wasi。插件的 world 导入对应的 WASI 接口后也可使用。
std.time
| 项 | 含义 |
|---|---|
now_ms() -> Float | 自 Unix 纪元起的毫秒数 |
monotonic_ms() -> Float | 从某个固定起点计算的毫秒数,仅差值有意义 |
utc_offset_minutes() -> Int | 本地时区与 UTC 的偏移分钟数 |
Instant.now()、instant.elapsed_ms() | 测量一段时长 |
sleep(ms) | 异步挂起当前任务,至少等待 ms 毫秒 |
yield_now() | 异步让出执行机会,之后再继续 |
import std.time
async fn main() {
let start = time.Instant.now()
time.sleep(20).await
print("{start.elapsed_ms() >= 20.0}")
print("{time.now_ms() > 1_700_000_000_000.0}")
}
true
true
std.random
| 项 | 含义 |
|---|---|
float() -> Float | [0, 1) 内的随机浮点数 |
int(lo, hi) -> Int | [lo, hi) 内的随机整数 |
bool() -> Bool | 随机布尔值 |
choice(xs) -> Option<T> | 随机取一个元素,空列表返回 None |
shuffle(xs) | 原地打乱列表 |
Rng.new(seed) | 创建确定性 xorshift64* 生成器,提供 next_u64、float 和 int |
模块函数使用宿主的随机源。需要重现结果时,给 Rng 固定的种子。
import std.random
fn main() {
let roll = random.int(1, 7)
print("{roll >= 1 && roll <= 6}")
let a = random.Rng.new(42)
let b = random.Rng.new(42)
print("{a.int(0, 100) == b.int(0, 100)}")
}
true
true
std.math 与 std.log
std.math
提供浮点常量、数学函数和整数辅助函数,所有目标均可用。
| 项 | 含义 |
|---|---|
PI、E、TAU | 常量 |
sqrt cbrt pow exp ln log2 log10 | 乘方、开方和对数 |
sin cos tan asin acos atan atan2 hypot | 三角函数及斜边长 |
floor ceil round abs | 取整与绝对值 |
gcd(a, b)、lcm(a, b) | Int 的最大公约数、最小公倍数 |
浮点数学函数也可用方法形式调用,math.sqrt(x) 等价于 x.sqrt()。
import std.math
fn main() {
let r = 2.0
print("{math.PI * r * r}")
print("{math.hypot(3.0, 4.0)} {math.gcd(12, 18)} {math.lcm(4, 6)}")
}
12.566370614359172
5.0 6 12
std.log
debug、info、warn、error 分别记录不同级别的日志,参数类型都是 Str。WASI 写到标准错误流,浏览器写到控制台,插件通过 wasi:logging/logging 写到宿主。插件的 world 未导入该接口时,日志会被丢弃。
import std.log
fn main() {
log.info("starting")
log.warn("disk almost full")
}
std.dom
用于访问浏览器文档,仅在 browser 目标提供。
import std.dom
fn main() {
let input = dom.create("input")
input.set_attr("placeholder", "type something")
let echo = dom.create("p")
input.on("input", |e| echo.set_text(e.value()))
let app = dom.query("#app").unwrap_or(dom.body())
app.append(input)
app.append(echo)
}
函数
| 函数 | 含义 |
|---|---|
query(selector) -> Option<Element> | 第一个匹配 CSS 选择器的元素 |
query_all(selector) -> List<Element> | 所有匹配元素 |
create(tag) -> Element | 创建尚未挂载的元素 |
body() -> Element | 文档的 body |
set_title(title) | 设置文档标题 |
Element
| 方法 | 含义 |
|---|---|
text()、set_text(s) | 读取或设置纯文本 |
set_html(s) | 用 HTML 替换内容 |
attr(name) -> Option<Str>、set_attr(name, value) | 读取或设置属性 |
value()、set_value(s) | 读取或设置表单控件的值 |
add_class(c)、remove_class(c)、toggle_class(c) | 管理 CSS 类 |
set_style(property, value) | 设置内联样式 |
append(child)、remove() | 添加子元素或移除自身 |
query(selector) -> Option<Element> | 第一个匹配的后代元素 |
on(event, f) | 每次事件发生时把 Event 传给 f |
Event
| 方法 | 含义 |
|---|---|
kind() | 事件类型,例如 click |
target() | 事件目标元素 |
key() | 键盘事件的键名,其他事件为空字符串 |
value() | 输入事件目标元素的值,其他事件为空字符串 |
prevent_default() | 取消浏览器的默认行为 |
Puddi 语言规范
本页翻译自 v0.1.2 的 SPEC.md。小节编号与英文原文及一致性用例一致。解释有出入时,以该发行版原文为准。覆盖情况见一致性测试。
版本为 0.1 草案。草案内容已齐备,第 14 节列出 v1 之后才考虑的功能。
1. 概览
Puddi 是一门静态类型、面向表达式的语言,编译为 WebAssembly。它以同一种源语言面向浏览器、WASI 运行时(服务器、边缘环境、命令行)及插件宿主,使用 WebAssembly 引擎的垃圾回收(WasmGC),通过组件模型与宿主交互。
| 主题 | 规定 |
|---|---|
| 编译目标 | 仅 WebAssembly,JavaScript 只用于加载 |
| 宿主 | browser、wasi(WASI 0.3)、plugin |
| 内存 | WasmGC |
| 类型 | 静态类型与局部类型推断 |
| 多态 | 泛型与名义特征,dyn Trait 用于动态分派 |
| 缺失值与错误 | 无 null,使用 Option<T>、Result<T, E>、支持 From 转换的 ?、Error 和 AnyErr,panic 触发陷阱 |
| 可变性 | let 与 var 绑定,逐字段声明可变性,对象值共享引用 |
| 数值 | Int 为 32 位有符号整数,溢出触发陷阱,无损拓宽隐式完成 |
| 字符串 | 不透明的 Str,不支持整数索引 |
| 异步 | async fn、后缀 .await、结构化并发 |
| 并行 | 独立工作线程通过消息通信,不共享内存 |
| 互操作 | 主要使用组件模型与 WIT;核心模块可用 @extern、@export |
| 元编程 | v1 只有编译器内建的 @derive |
| 语法 | 花括号、可选分号、面向表达式 |
| 工具链 | pud、pud.toml、基于 Git 的包 |
| 源文件 | UTF-8 编码,扩展名 .pud |
2. 词法结构
2.1 源文本
源文件用 UTF-8 编码,扩展名为 .pud。标识符遵循 Unicode UAX #31,以 XID_Start 开头,后跟 XID_Continue。单独的 _ 是通配符,不是标识符。
2.2 注释
// line comment
/* block comment, may nest */
/// doc comment, attached to the next declaration
2.3 关键字
as async await break const continue dyn else
enum export false fn for if impl import
in let loop match pub return self Self
struct test trait true type var while
2.4 命名约定
类型、特征和枚举变体采用 UpperCamelCase,函数、变量、字段和模块采用 snake_case,常量采用 SCREAMING_SNAKE_CASE。pud fmt 不会重命名,命名违反约定时应由编译器发出警告。
2.5 语句结束
换行结束语句。可用分号在同一行分隔多条语句。分号仅作分隔符,不改变表达式含义。
以下情况换行不结束语句:
- 位于尚未闭合的
(或[中 - 行尾是二元运算符或逗号
- 下一行以
.开头
let total = price * count +
shipping // continues: line ends with +
let names = users
.filter(|u| u.active) // continues: next line starts with .
.map(|u| u.name)
结构体、枚举、特征和 match 的成员以换行或逗号分隔。
2.6 数值字面量
42 1_000 0xFF 0b1010 0o17
3.14 1e9 2.5e-3
整数字面量的类型取自上下文,默认为 Int。浮点字面量同理,默认为 Float。超出对应类型范围的字面量是编译错误。
2.7 字符字面量
Char 表示 Unicode 标量值,以单引号书写,例如 'a'、'\n'、'\u{1F600}'。
2.8 字符串字面量
字符串以双引号书写,支持 {expr} 插值。被插入的表达式必须实现 Show。普通花括号写作 \{ 或 \}。
let s = "hi {name}, you have {count + 1} messages"
let t = "a literal \{brace\}"
支持的转义为 \n \r \t \0 \\ \" \' \{ \} \u{...}。
3. 类型
3.1 类型推断
类型推断是局部的。顶层函数签名须写出参数类型和返回类型。省略返回类型表示 ()。局部绑定、闭包以及函数体中表达式的类型可推断。
fn area(w: Int, h: Int) -> Int {
let s = w * h // inferred Int
s
}
3.2 内建类型
| 类别 | 类型 |
|---|---|
| 布尔 | Bool |
| 整数 | Int(同 I32)、I8 I16 I32 I64 U8 U16 U32 U64 |
| 浮点 | Float(同 F64)、F32 F64 |
| 文本 | Char、Str |
| 单元 | () |
| 元组 | (A, B, ...) |
| 函数 | fn(A, B) -> R |
| 集合 | List<T>、Map<K, V>、Set<T> |
| 核心枚举 | Option<T>、Result<T, E> |
3.3 结构体
struct Point {
x: Int
var y: Int
}
struct Pair<A, B> { a: A, b: B }
字段默认仅对所属模块可见,用 pub 公开。声明为 var 的字段在构造后可以赋值,其余字段不允许赋值(见 4.1)。
构造时按名称指定字段,支持字段简写及更新语法:
let p = Point { x: 1, y: 2 }
let q = Point { x, y } // shorthand for x: x, y: y
let r = Point { x: 5, ..p } // copy remaining fields from p
3.4 枚举
枚举是代数数据类型。变体可以无载荷、带元组字段或带具名字段。
enum Shape {
Circle(Float)
Rect { w: Float, h: Float }
Empty
}
let s = Shape.Circle(2.0)
对枚举的 match 必须穷尽所有变体。
3.5 元组与单元类型
元组类型写作 (Int, Str),用 (1, "a") 等表达式构造,用 t.0、t.1 等访问字段。单元类型及其唯一的值均写作 ()。
3.6 函数类型与闭包
函数值的类型写作 fn(Int, Int) -> Int。命名函数和闭包均可转成函数类型。异步函数类型写作 async fn(Int) -> Str。
3.7 数值类型
Int 对应 Wasm i32,I64 和 U64 对应 i64,Float 对应 f64,F32 对应 f32。I8、I16、U8、U16、U32 以 i32 存储,由编译器约束取值范围。
整数溢出、除以零或对零取余触发陷阱。整数除法向零截断,余数与被除数同号。回绕、饱和、受检查运算可通过 wrapping_add、saturating_add、checked_add 等显式方法选择。
拓宽:总是无损的转换可以隐式发生。
| 原类型 | 可隐式拓宽到 |
|---|---|
I8 | I16 I32 I64 F32 F64 |
I16 | I32 I64 F32 F64 |
I32 | I64 F64 |
U8 | U16 U32 U64 I16 I32 I64 F32 F64 |
U16 | U32 U64 I32 I64 F32 F64 |
U32 | U64 I64 F64 |
F32 | F64 |
F64 无法精确表示每个 64 位整数,因此 I64、U64 不会隐式拓宽为浮点数。
预期类型已知时允许拓宽,包括带类型标注的绑定、函数实参、返回值、字段初始化和集合元素。二元运算两侧的数值类型不同时,拓宽到能无损容纳两侧的最窄类型。若不存在这样的类型(如 I64 与 U64、I64 与 Float),则编译失败。
窄化:可能有损的转换必须显式指定。to_<type>() 返回 Option,无法转换时返回 None。也可选择 truncate_to_int()、round_to_int()、wrap_to_u8() 等显式的有损转换方法。
let a: Int = 5
let b: I64 = a // ok, widening
let c: Int = b.to_int()? // narrowing, returns Option<Int>
3.8 字符串与字符
Str 是不可变、不透明的 Unicode 字符串,不支持整数索引。可用以下方式访问文本:
s.chars()按码点遍历,产生Chars.graphemes()按字素簇遍历,产生Strs.find("x")返回Option<StrIndex>,s.slice(start, end)接受StrIndex,该索引不透明且只对生成它的字符串有效
字符串不提供取决于表示方式的 len()。按需使用 s.chars().count()、s.graphemes().count() 或 s.utf8_len()。实现可自选内部表示,包括宿主原生字符串。
3.9 集合
| 类型 | 写法 | 规则 |
|---|---|---|
List<T> | [1, 2, 3] | 可增长数组 |
Map<K, V> | ["a": 1, "b": 2],空映射为 [:] | K: Eq + Hash,保留插入顺序 |
Set<T> | Set.from([1, 2, 3]) | T: Eq + Hash,保留插入顺序 |
列表 xs[i] 要求 Int 索引,越界触发陷阱。xs.get(i) 返回 Option<T>。映射的 m[k] 在键缺失时触发陷阱,m.get(k) 返回 Option<V>。
集合同其他对象一样是引用。List、Map、Set 提供 push、insert、remove 等修改方法;ListView、MapView、SetView 只提供读取方法,可由对应集合隐式转换而来。
3.10 Option 与 Result
Puddi 没有 null。Option<T> 用 Some(v) 或 None 表示值可能缺失,Result<T, E> 用 Ok(v) 或 Err(e) 表示操作可能失败。它们是普通枚举,其变体由预导入项引入,因此可省略路径。? 见第 6 节。
3.11 泛型
类型参数用尖括号书写,类型约束跟在 : 后,可以用 + 连接。
fn largest<T: Ord>(xs: List<T>) -> Option<T> { ... }
fn dump<T: Show + Hash>(x: T) { ... }
struct Stack<T> { var items: List<T> }
可在调用处推断类型实参,也可显式提供,例如 parse<Int>(s)。
3.12 特征
特征是名义性的。类型仅通过显式 impl 块实现特征。特征可以包含默认方法、关联类型和父特征。Self 指实现该特征的类型。
trait Show {
fn show(self) -> Str
}
trait Iterator {
type Item
fn next(self) -> Option<Self.Item>
}
trait Shape: Show {
fn area(self) -> Float
fn describe(self) -> Str { "{self.show()} with area {self.area()}" }
}
impl Show for Point {
fn show(self) -> Str { "({self.x}, {self.y})" }
}
impl<T: Show> Show for List<T> {
fn show(self) -> Str { ... }
}
一致性:impl Trait for Type 只能位于定义 Trait 或 Type 的包中。给定类型最多存在一个适用的实现。
异步方法:特征方法可以是 async fn。
运算符特征:通过实现以下标准特征重载运算符。
| 运算符 | 特征 |
|---|---|
+ - * / % | Add Sub Mul Div Rem |
一元 - ! | Neg Not |
== != | Eq |
< <= > >= | Ord |
a[i] | Index |
for x in a | Iterable |
"{a}" | Show |
3.13 派生
@derive 指示编译器生成标准特征的实现。v1 仅支持派生内建的 Eq、Ord、Hash、Show、Transfer(见 9.4)。
@derive(Eq, Ord, Hash, Show)
struct Point { x: Int, y: Int }
3.14 特征对象
dyn Trait 可持有任何实现了 Trait 的值。调用在运行时通过虚表分派。预期类型为 dyn Trait 时,值可隐式转换。
let items: List<dyn Show> = [Point.new(1, 2), "hi", 42]
for it in items { print(it.show()) }
特征只有在方法没有自己的类型参数,且没有在接收者以外的位置引用 Self 时,才可用作特征对象。关联类型须固定,例如 dyn Iterator<Item = Int>。
特征对象支持异步方法。通过特征对象调用异步方法返回堆上分配的 future。由于 WasmGC 对象本来就在堆上,除动态分派外仅引入少量额外成本。
3.15 类型别名
type UserId = Int
type Callback<T> = fn(T) -> ()
类型别名是目标类型的另一个名称。别名可以引用后续声明,展开时须无循环依赖。
4. 表达式与语句
块、if、match 和 loop 产生值。块的最后一个表达式给出块的值;预期类型为 () 时丢弃该值。赋值运算(=、+= 等)本身是类型为 () 的表达式。
4.1 绑定与可变性
let 声明不可重新赋值的绑定,var 声明可重新赋值的绑定。两者都可接受模式。绑定的可变性只控制对该绑定重新赋值。
字段的可变性在类型中声明。只有 var 字段在构造后允许赋值,直接对应 WasmGC 的可变与不可变字段。
结构体、枚举与集合的值是引用。赋值和传参共享对象。
struct Point {
x: Int // immutable
var y: Int // mutable
}
let p = Point { x: 1, y: 2 }
p.y = 5 // ok, y is var
p.x = 5 // error: x is immutable
p = Point { x: 0, y: 0 } // error: p is let
let q = p // q and p refer to the same object
== 调用 Eq 比较。用预导入的 same(a, b) 检查引用标识。
4.2 运算符与优先级
从高到低如下。
| 级别 | 运算符 | 结合方向 |
|---|---|---|
| 1 | .field .method() f() a[i] ? .await | 左 |
| 2 | 一元 - ! | 前缀 |
| 3 | * / % | 左 |
| 4 | + - | 左 |
| 5 | << >> | 左 |
| 6 | & | 左 |
| 7 | ^ | 左 |
| 8 | | | 左 |
| 9 | == != < <= > >= | 不结合 |
| 10 | && | 左 |
| 11 | || | 左 |
| 12 | .. ..= | 不结合 |
| 13 | = += -= *= /= %= &= |= ^= <<= >>= | 右 |
&& 与 || 短路求值。a..b 右端不包含,a..=b 包含右端。
4.3 块与控制流
let sign = if x > 0 { 1 } else if x < 0 { -1 } else { 0 }
let label = match code {
200 -> "ok"
404 -> "not found"
500..=599 -> "server error"
_ -> "other"
}
没有 else 的 if 类型为 ()。if、while 与 match 条件中的结构体字面量必须用括号包裹。
4.4 模式
模式可解构元组、结构体和枚举变体,可以出现在 let、var、match、for、if let、while let 和 let ... else 中。
| 模式 | 例子 |
|---|---|
| 通配 | _ |
| 绑定 | x |
| 字面量 | 42、"hi"、'a'、true |
| 区间 | 1..=9、'a'..='z' |
| 元组 | (a, _, c) |
| 结构体 | Point { x, y: 0 }、Point { x, .. } |
| 枚举变体 | Some(v)、Shape.Rect { w, h } |
| 或模式 | A | B |
| 列表 | [first, ..rest]、[] |
match 分支可附加 if 守卫。
let (a, b) = pair
match shape {
Shape.Circle(r) if r > 10.0 -> "big circle"
Shape.Circle(_) -> "circle"
Shape.Rect { w, h } -> "rect {w}x{h}"
Shape.Empty -> "nothing"
}
if let Some(user) = find(id) { greet(user) }
let Some(cfg) = load() else { return }
let ... else 的 else 块必须分岔,例如 return、break、continue 或 panic。
4.5 循环
for x in xs { ... }
for (i, x) in xs.enumerate() { ... }
for i in 0..10 { ... }
while cond { ... }
while let Some(job) = queue.pop() { ... }
let found = loop {
if done() { break value }
}
break 可以给出 loop 表达式的结果。for、while 类型均为 ()。for x in e 要求 e 的类型实现 Iterable。
4.6 闭包
let inc = |x| x + 1
let add = |a: Int, b: Int| -> Int { a + b }
let fetch = async |url| { http.get(url).await }
闭包按引用捕获变量。捕获 var 绑定的闭包可看见之后的赋值,也可以对它赋值。
4.7 路径
模块成员、枚举变体和关联函数统一用 . 分隔,例如 io.read、Shape.Circle、Point.new(1, 2)。
5. 声明
5.1 函数
fn add(a: Int, b: Int) -> Int { a + b }
async fn load(url: Str) -> Result<Str, HttpErr> { ... }
return 携带值提前退出。未提前退出时函数返回函数体块的值。
5.2 方法
固有方法在 impl 块内声明,第一个参数为 self。不带 self 的是关联函数。值是引用且可变性逐字段声明,因此无需单独的可变接收者。
impl Point {
fn new(x: Int, y: Int) -> Point { Point { x, y } }
fn len(self) -> Float { ... }
fn move_down(self, dy: Int) { self.y += dy }
}
let p = Point.new(1, 2)
p.len()
5.3 常量
const MAX_USERS: Int = 1_000
const GREETING: Str = "hi"
常量的初始化表达式必须是常量表达式,包括字面量、其他常量、在常量上的算术和比较,以及由常量表达式构造的结构体、元组和枚举。初始化表达式中的名称在声明该常量的模块中解析。
5.4 可见性
声明和结构体字段默认仅在所在模块可见。pub 将它们公开给其他模块和包。export 标记组件导出(见第 8 节)。
5.5 属性
属性以 @ 开头,应用于下一个声明。
| 属性 | 含义 |
|---|---|
@derive(...) | 生成标准特征实现(3.13) |
@target(t) | 仅在 browser、wasi 或 plugin 指定目标构建时保留声明,可组合为 @target(wasi, plugin) |
@extern(module, name) | 核心 Wasm 导入(8.4) |
@export(name) | 核心 Wasm 导出(8.4) |
@deprecated(msg) | 使用时发出警告 |
5.6 测试
test 块可写在任意文件中,仅由 pud test 编译。每项测试在新实例运行,发生 panic 或断言失败导致陷阱时测试失败。测试体可使用 .await。
test "addition works" {
assert_eq(add(2, 2), 4)
}
6. 错误处理
6.1 问号运算符
后缀 ? 取出 Ok 或 Some 中的值,否则让当前函数提前返回 Err 或 None。如果 Result 的错误类型与函数返回的错误类型不同,? 通过 From 转换。
enum AppErr {
Io(IoErr)
Bad
}
impl From<IoErr> for AppErr {
fn from(e: IoErr) -> AppErr { AppErr.Io(e) }
}
fn load(path: Str) -> Result<Config, AppErr> {
let text = fs.read(path)? // IoErr converted to AppErr
parse(text).ok_or(AppErr.Bad)
}
在返回 Option 的函数内才可对 Option 使用 ?。
6.2 Panic
panic(msg) 表示无法恢复的错误。断言失败、整数溢出、除以零和索引越界也会导致 panic。它使 Wasm 实例触发陷阱,在 Puddi 内部无法捕获。插件发生陷阱时由宿主接收,宿主进程继续运行。
6.3 Error 与 AnyErr
错误类型宜实现 Error。
trait Error: Show {
fn source(self) -> Option<dyn Error> { None }
}
source 返回底层错误(若有),可据此遍历并显示错误链。
AnyErr 包装任意实现了 Error 的值。标准库提供 impl<E: Error> From<E> for AnyErr,因此 ? 能自动转换这些错误。库宜返回自己的错误类型,应用可用 AnyErr 省去手写的 From 实现。
fn main() -> Result<(), AnyErr> {
let s = fs.read(path)? // IoErr -> AnyErr
let v = json.decode(s)? // ParseErr -> AnyErr
...
}
e.downcast<E>() 返回 Option<E>,可恢复原始错误。AnyErr 通过委托被包装的值实现 Error。
6.4 main 的错误
当 E 实现 Show 时,main 可返回 Result<(), E>。返回 Err 时输出错误,wasi 上程序以失败状态退出,browser 上报告到控制台。
7. 模块与包
7.1 模块
每个文件是一个模块。模块路径按 src/ 下的路径确定,例如 src/net/http.pud 是 net.http。src/main.pud 是程序根模块,库的根模块为 src/lib.pud。
import net.http // use as http.get(...)
import net.http.{get, Request} // import specific names
import net.http as h // alias
import json // dependency named in pud.toml
import std.fs // standard library
包内模块之间可循环导入,包之间的依赖必须无环。
7.2 清单
[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"
[deps]
json = "github.com/someone/puddi-json@1.2"
[target.wasi]
world = "wasi:cli/command"
[target.plugin]
world = "wit/host.wit#plugin"
pud.lock 记录每个依赖的确切提交,并纳入版本控制。
7.3 依赖
依赖由 Git 仓库和语义化版本标签(如 v1.2.0)标识。pud.toml 声明的是最低版本。最小版本选择为每个依赖选择满足所有约束的最低版本,因此没有锁文件时也可得到相同的版本选择。同一包的不同主版本视为不同包,可共存。
7.4 工具链
工具链通过 pud 命令提供。
| 命令 | 用途 |
|---|---|
pud new <name> | 创建包 |
pud build [--target t] | 构建 browser、wasi 或 plugin |
pud run | 构建并运行,WASI 用运行时,浏览器用开发服务器 |
pud test | 执行测试块 |
pud fmt | 按不可配置的统一格式整理代码 |
pud doc | 根据 /// 注释生成文档 |
pud add <dep> | 添加依赖 |
8. 宿主互操作
8.1 目标
| 目标 | 输出 | 入口 |
|---|---|---|
browser | 组件与生成的 JS 加载器 | fn main()、async fn main() 和/或 export fn |
wasi | [target.wasi] world 的 WASI 0.3 组件,默认 wasi:cli/command | 命令用 fn main() 或 async fn main(),其他 world 用 export fn |
plugin | [target.plugin] 中宿主 world 的组件 | world 所要求的导出 |
编译器检查每个所需导出都已提供且签名匹配。wasi 目标需要 WASI 0.3,并用其原生异步机制,不生成 WASI 0.2 产物。
8.2 组件模型
组件模型是主要的互操作方式。导入 WIT 接口会生成有类型的绑定,export fn 将函数声明为组件导出。
import wasi:cli/stdout
import wasi:http/outgoing-handler
export fn run() -> Result<(), AppErr> { ... }
8.3 WIT 类型映射
| WIT | Puddi |
|---|---|
bool | Bool |
s8 s16 s32 s64 | I8 I16 I32 I64 |
u8 u16 u32 u64 | U8 U16 U32 U64 |
f32 f64 | F32 F64 |
char | Char |
string | Str |
list<T> | List<T> |
option<T> | Option<T> |
result<T, E> | Result<T, E> |
tuple<...> | 元组 |
record | struct |
variant、enum | enum |
flags | 生成带 Bool 字段的结构体 |
resource | 不透明句柄类型,可提供方法 |
8.4 核心 Wasm 互操作
原始导入与导出直接作用于核心模块。仅数值类型与 Str 可直接跨越此边界,其他类型需手动编解码。
@extern("env", "log")
fn log(msg: Str)
@export("run")
fn run() { log("hi") }
9. 并发
9.1 异步函数
异步显式使用 async fn 与后缀 .await。异步函数、异步闭包和测试体内才允许等待。
async fn fetch_user(id: Int) -> Result<User, HttpErr> {
let res = http.get("/u/{id}").await?
res.json().await
}
9.2 结构化并发
并发子任务在作用域中启动,不可超出作用域。作用域会等全部子任务完成。子任务失败或作用域提前退出时会取消尚未完成的子任务。
async fn load_all() -> Result<(A, B), AppErr> {
task.scope(async |s| {
let a = s.spawn(load_a())
let b = s.spawn(load_b())
(a.await?, b.await?)
}).await
}
spawn 必须通过任务作用域调用。
9.3 取消
取消采用协作方式。任务在下一处 .await 遇到取消时提前停止,不继续执行其后的代码。长时间运行的同步循环可使用 task.is_cancelled() 主动检查。
9.4 工作线程
由于 WasmGC 对象尚不能跨线程共享,Puddi 的并行任务在工作线程运行。每个工作线程有独立的 Wasm 实例和堆,仅通过消息传递通信。
工作线程由任务作用域启动,运行顶层异步函数,结束时随作用域终止。闭包不能离开自己的实例,因此不能作为工作线程入口。线程内的 worker.Port<In, Out> 接收 In、发送 Out。s.worker(f) 返回的外部句柄则发送 In、接收 Out。
import std.worker
@derive(Transfer)
struct Job { id: Int, data: List<Int> }
async fn summer(port: worker.Port<Job, Int>) {
while let Some(job) = port.recv().await {
port.send(job.data.sum())
}
}
async fn main() {
task.scope(async |s| {
let w = s.worker(summer)
w.send(Job { id: 1, data: [1, 2, 3] })
let total = w.recv().await // Option<Int>
print("{total}")
}).await
}
消息在实例之间深拷贝,其类型必须实现 Transfer。数值、Bool、Char、Str 以及由可传输类型组成的元组、Option、Result、集合支持它。字段均可传输的结构体和枚举可派生它。函数值、闭包和 dyn 值不可传输。
browser 提供基于 Web Workers 的 std.worker。其他目标只有在 world 提供工作线程接口时可用。
10. 标准库
10.1 预导入项
每个模块都可无须导入使用:
- 类型:
Bool、Int、Float、固定宽度的数值类型、Char、Str、List、Map、Set、Option、Result、AnyErr - 变体:
Some、None、Ok、Err - 特征:
Eq、Ord、Hash、Show、From、Error、Transfer、Add、Sub、Mul、Div、Rem、Neg、Not、Index、Iterable、Iterator - 函数:
print、panic、assert、assert_eq、same
print 在 wasi 写一行到标准输出,在 browser 写到控制台,在 plugin 写到 std.log。
10.2 各目标的模块
导入目标未提供的模块会导致编译错误。
| 模块 | browser | wasi | plugin |
|---|---|---|---|
| 核心(预导入项和内置集合) | 是 | 是 | 是 |
std.bytes、std.collections、std.csv、std.date、std.encoding、std.fmt、std.iter、std.math、std.path、std.stats、std.text | 是 | 是 | 是 |
std.json | 是 | 是 | 是 |
std.log | 是 | 是 | 是 |
std.time | 是 | 是 | 依赖宿主 |
std.random | 是 | 是 | 依赖宿主 |
std.http | 是 | 是 | 依赖宿主 |
std.worker | 是 | 依赖宿主 | 依赖宿主 |
std.io | — | 是 | — |
std.fs | — | 是 | — |
std.env | — | 是 | — |
std.dom | 是 | — | — |
“依赖宿主”表示目标 world 须包含相应接口。插件的 std.log 在宿主有日志接口时写入它,否则不执行输出。
10.3 便携模块
按名称导入模块。例如,使用 import std.csv 后即可调用 csv.parse。
| 模块 | API | 行为 |
|---|---|---|
std.bytes | Endian.Big、Endian.Little、pack_u16、pack_u32、pack_u64、Reader | 读取器创建时复制输入。它提供 read、read_u8、指定字节序的整数读取以及 skip、position 和 remaining。读取或跳过失败时位置不变。 |
std.collections | Deque<T>、PriorityQueue<T>、count_by、group_by | 双端队列两端的插入和移除具有摊还常数复杂度。优先队列以对数时间弹出最小值。分组保持组内的输入顺序。 |
std.csv | parse、stringify、Format.new | 支持带引号的字段、双引号转义以及 LF、CRLF 或 CR 行尾,同一输入可有不同列数。Format 的分隔符可用制表符或双引号以外的可打印 ASCII 字符。写出时使用 CRLF,并将无字段行写成一个空字段。解析错误带从零开始的字节偏移。 |
std.date | Date、DateTime、days_in_month、is_leap_year | 支持 0001 至 9999 年的公历。日期格式为 YYYY-MM-DD,可与自 1970-01-01 起的天数互转。时间戳格式为 YYYY-MM-DDTHH:MM:SSZ,可与 Unix 秒数互转。无效或越界值返回 None。 |
std.encoding | hex_encode、hex_decode、base64_encode、base64_decode、base64url_encode、base64url_decode、percent_encode、percent_decode | 十六进制接受两种大小写并写出小写。Base64 使用标准填充,Base64url 使用 URL 安全字符且无填充。百分号编码保留 ASCII 字母、数字和 -、.、_、~,百分号解码保留原样的加号。解码返回字节或带字节偏移的错误。 |
std.fmt | join、int_radix、uint_radix、parse_int_radix、parse_uint_radix | 通过 Show 拼接值。整数格式化和解析支持 2 至 36 进制。输出使用小写,解析接受两种大小写,有符号解析接受可选的正负号。无效输入和溢出返回 None。 |
std.iter | once、repeat、from_fn、unfold | 从值、回调或状态转换创建惰性迭代器。repeat 生成无限序列。基于回调的序列遇到第一个 None 时结束。 |
std.json | parse、stringify、pretty、Json.at_pointer | 支持紧凑输出和两空格缩进。指针用斜杠分段查找对象键和数组下标。~0 代表波浪号,~1 代表斜杠,空指针选中根值。指针无效或值缺失时返回 None。 |
std.path | is_absolute、normalize、join、parent、file_name、stem、extension | 以文本规则处理斜杠分隔的路径。开头的斜杠表示根目录,join 的右侧为绝对路径时替换左侧。空相对路径规范化为 .。 |
std.stats | summarize、median | 摘要包含计数、均值、极值、总体与样本方差及标准差。空样本、非有限值或摘要溢出返回 None。少于两个观测值时样本方差返回 None。 |
std.text | strip_prefix、strip_suffix、truncate、pad_start、pad_end | 截断长度和填充宽度按 Unicode 标量计数。前后缀精确匹配。 |
import std.collections
import std.csv
fn main() {
let rows = csv.parse("fruit,red\nfruit,green\nvegetable,green").unwrap()
let colors = collections.count_by(rows, |row| row[1])
print(colors["green"])
}
11. 文法摘要
以下是非正式 EBNF。sep 表示 2.5 允许的换行、; 或 ,。
file = { import } { item } ;
import = "import" mod_path [ "." "{" ident { "," ident } "}" ] [ "as" ident ]
| "import" wit_name ;
item = { attribute } [ "pub" | "export" ]
( fn_decl | struct_decl | enum_decl | trait_decl | impl_decl
| type_alias | const_decl | test_decl ) ;
attribute = "@" ident [ "(" [ attr_arg { "," attr_arg } ] ")" ] ;
fn_decl = fn_sig [ block ] ; (* no block only with @extern *)
fn_sig = [ "async" ] "fn" ident [ generics ] "(" [ params ] ")" [ "->" type ] ;
params = param { "," param } [ "," ] ;
param = "self" | ident ":" type ;
generics = "<" gparam { "," gparam } ">" ;
gparam = ident [ ":" bound { "+" bound } ] ;
struct_decl = "struct" ident [ generics ] "{" { field sep } "}" ;
field = [ "pub" ] [ "var" ] ident ":" type ;
enum_decl = "enum" ident [ generics ] "{" { variant sep } "}" ;
variant = ident [ "(" type { "," type } ")" | "{" { field sep } "}" ] ;
trait_decl = "trait" ident [ generics ] [ ":" bound { "+" bound } ]
"{" { ( "type" ident | fn_decl ) sep } "}" ;
impl_decl = "impl" [ generics ] [ type_path "for" ] type
"{" { ( fn_decl | "type" ident "=" type ) sep } "}" ;
type_alias = "type" ident [ generics ] "=" type ;
const_decl = "const" ident ":" type "=" expr ;
test_decl = "test" string_lit block ;
type = type_path | "dyn" type_path | "Self"
| "(" [ type { "," type } ] ")"
| [ "async" ] "fn" "(" [ type { "," type } ] ")" [ "->" type ] ;
type_path = path [ "<" type_arg { "," type_arg } ">" ] ;
type_arg = type | ident "=" type ;
block = "{" { stmt sep } [ expr ] "}" ;
stmt = ( "let" | "var" ) pattern [ ":" type ] "=" expr [ "else" block ]
| expr ;
expr = (* operators per 4.2 *) unary { binop unary } ;
unary = { "-" | "!" } postfix ;
postfix = primary { "." ident [ call_args ] | "." int_lit | call_args
| "[" expr "]" | "?" | ".await" } ;
call_args = [ "<" type { "," type } ">" ] "(" [ expr { "," expr } [ "," ] ] ")" ;
primary = literal | path | block | "(" expr ")" | tuple
| list_lit | map_lit | struct_lit
| if_expr | match_expr | loop_expr | while_expr | for_expr | closure
| "return" [ expr ] | "break" [ expr ] | "continue" ;
if_expr = "if" cond block [ "else" ( if_expr | block ) ] ;
cond = expr | "let" pattern "=" expr ;
match_expr = "match" expr "{" { pattern [ "if" expr ] "->" expr sep } "}" ;
loop_expr = "loop" block ;
while_expr = "while" cond block ;
for_expr = "for" pattern "in" expr block ;
closure = [ "async" ] "|" [ cparam { "," cparam } ] "|" [ "->" type ] expr ;
cparam = pattern [ ":" type ] ;
list_lit = "[" [ expr { "," expr } [ "," ] ] "]" ;
map_lit = "[" ":" "]" | "[" expr ":" expr { "," expr ":" expr } [ "," ] "]" ;
struct_lit = path "{" [ field_init { "," field_init } ] [ "," ".." expr ] "}" ;
field_init = ident [ ":" expr ] ;
pattern = pat_atom { "|" pat_atom } ;
pat_atom = "_" | literal | literal ( ".." | "..=" ) literal | ident
| path [ "(" [ pattern { "," pattern } ] ")"
| "{" [ fpat { "," fpat } ] [ "," ".." ] "}" ]
| "(" [ pattern { "," pattern } ] ")"
| "[" [ pattern { "," pattern } ] [ "," ".." ident ] "]" ;
fpat = ident [ ":" pattern ] ;
12. 实现注记
本节不规定语言行为。
- 泛型经单态化处理
- 结构体映射到 WasmGC 结构体,
var字段可变,其余字段不可变 - 枚举以 WasmGC 基结构体表示,各变体是子类型。
match编译成br_on_cast链或标签分派 - 特征对象包含一对引用,分别指向虚表和数据
- 闭包结构体包含函数引用及捕获环境,捕获的
var存在独立对象中 - 字符串可以在浏览器使用 JS String Builtins,在其他宿主使用 UTF-8 GC 数组
- 异步在浏览器基于 JSPI,在 WASI 0.3 基于原生异步
- 浏览器的每个工作线程对应一个运行独立实例的 Web Worker
- 溢出检查由原生运算、检测和陷阱组成
13. 示例
以下是规范中的说明性示例。可直接运行的实现见内置 Todo 示例,其中手动将 JSON 值转换成结构体。
// src/main.pud, built with: pud build --target wasi
import std.fs
import json
@derive(Eq, Show)
struct Todo {
title: Str
var done: Bool
}
enum AppErr {
Io(fs.IoErr)
Parse(json.ParseErr)
}
impl From<fs.IoErr> for AppErr {
fn from(e: fs.IoErr) -> AppErr { AppErr.Io(e) }
}
impl From<json.ParseErr> for AppErr {
fn from(e: json.ParseErr) -> AppErr { AppErr.Parse(e) }
}
fn load(path: Str) -> Result<List<Todo>, AppErr> {
let text = fs.read(path)?
let todos: List<Todo> = json.decode(text)?
Ok(todos)
}
fn main() {
let todos = match load("todos.json") {
Ok(t) -> t
Err(e) -> {
print("could not load: {e}")
return
}
}
let pending = todos.filter(|t| !t.done)
print("{pending.len()} of {todos.len()} left")
for t in pending {
print(" - {t.title}")
}
}
test "empty list has nothing pending" {
let todos: List<Todo> = []
assert_eq(todos.filter(|t| !t.done).len(), 0)
}
14. 推迟到 v1 之后的功能
- 共享内存线程,等待 WasmGC 支持跨线程共享对象
where子句- 常量泛型
- 自定义派生与编译期执行
一致性测试套件
语言规范定义 Puddi。编译器仓库的测试套件通过外部命令检查 pud 是否符合规范。
- 每个用例注明对应的规范小节
- 第 2 至 10 章的每个规范小节至少有一个通过的用例,否则严格覆盖率检查失败
xfail表示记录在案的实现差异。如果该用例开始通过,套件会报错,直到移除标记
v0.1.2 的每个规范性小节都有通过的用例。发行流程会对每个原生平台的二进制运行一致性测试。
运行
需要 Node.js 22 或更新版本。可以传入任意待检查的 pud,包括安装的发行版。
git clone https://github.com/puddi-lang/puddi
cd puddi
node conformance/run.mjs --pud ~/.pud/bin/pud --coverage
| 选项 | 含义 |
|---|---|
--pud <path> | 待检查二进制,默认依次查找 target/release/pud、target/debug/pud 和 PATH |
--filter <text> | 按小节号或用例路径筛选 |
--coverage | 输出各小节覆盖情况 |
--strict-coverage | 缺少通过用例的规范小节使检查失败 |
--json <file> | 输出 JSON 报告 |
--list | 只列出用例 |
--jobs <n> | 限制同时运行的用例数 |
--timeout <seconds> | 限制单个用例的时间 |
0.1 的已知差异
下表记录 v0.1.0 和 v0.1.1 的差异。相应用例已在 v0.1.2 中通过。
| 小节 | 差异 |
|---|---|
| 2.4 | 命名不合规时未发出警告 |
| 2.4 | 结构体字面量要求类型名以大写字母开头 |
| 3.7 | U8 + 0.5 不将右侧字面量默认推断为 Float |
| 3.12 | 在 impl 内不能解析 Self.Item |
| 3.12 | 重复的 impl 被接受 |
| 4.6 | let inc = |x| x + 1 需要参数标注 |
| 8.3 | 使用 WIT 记录、变体、枚举或标志位的导出无法编译 |
编写用例
用例可为单个 .pud 文件或一个小包。在源文件开头以 // 标注规范小节和执行模式,用 //> 声明预期输出。规范行为发生变化时应同时补充用例。详见用例格式与参与贡献。
实现状态
一致性测试套件按 Puddi 0.1 语言规范草案检查 pud 的行为。
语言
支持结构体、枚举、元组、带约束且单态化的泛型、默认方法、关联类型、父特征、dyn Trait、运算符特征、引用捕获闭包和带穷尽性检查的模式匹配。模式包括守卫、区间、或模式、列表模式、let ... else、if let、while let。
还支持 ? 与 From 错误转换、AnyErr.downcast、@derive(Eq, Ord, Hash, Show, Transfer)、常量、类型别名、async fn、.await、结构化取消、工作线程、隐式数值拓宽、整数溢出检查、模块、WIT 导入、test、@target、@extern、@export、export fn 和 @deprecated。
标准库
已知限制
std.io、std.fs、std.env仅在wasi上提供,std.dom仅在browser上提供- 外部 WASI 宿主须实现
puddi:runtime工作线程接口,才能运行使用工作线程的组件 - 内嵌运行时链接 Wasmtime 的 WASI 0.3.0,通过语义化版本匹配满足 0.3.2 接口导入
pud test运行在 JavaScript 宿主,不能调用 WIT 导入- 字素分割为近似实现,能处理组合标记、变体选择符和零宽连接序列。大小写转换仅覆盖 ASCII
v1 之后
草案将共享内存线程、where 子句、常量泛型、自定义派生和编译期执行留到 v1 之后。
编译器开发
Puddi 将源码和 WIT 绑定编译为 WebAssembly。主分支的完整流程见编译器架构。
| 阶段 | 工作 | 文件入口 |
|---|---|---|
| 源码加载 | 查找模块、解析依赖、生成 WIT 绑定 | src/main.rs、src/deps.rs、src/wit.rs |
| 前端 | 分词、语法分析、展开派生、解析名称 | src/lexer.rs、src/parser.rs、src/derive.rs、src/program.rs |
| 类型检查和降级 | 检查类型与模式、单态化泛型、生成有类型的 IR | src/elab.rs、src/exhaust.rs、src/ir.rs |
| WebAssembly | 生成 WasmGC 类型和指令、编码核心模块并封装组件 | src/codegen.rs、src/wit.rs |
| 宿主 | 在 Wasmtime 中运行组件,或由 JavaScript 宿主加载核心模块 | src/runner.rs、src/runtime.mjs |
优化与诊断
Puddi v0.1.1 引入 IR 优化、内置 WebAssembly 汇编器、并行解析与代码生成,并缓存构建产物和 Wasmtime 机器码。详情见 v0.1.1 发行说明。
| 环境变量 | 用途 |
|---|---|
PUD_TIME=1 | 打印各阶段的耗时 |
PUD_NO_CACHE=1 | 关闭构建与 Wasmtime 缓存 |
PUD_NO_OPT=1 | 跳过 IR 优化 |
PUD_WAT=1 | 使用 wat crate 替代内建汇编器 |
PUD_ASM_CHECK=1 | 用两套汇编实现生成并比较结果 |
PUD_SERIAL_CODEGEN=1 | 单线程生成 WebAssembly 文本 |
选择测试类型
语言规范规则发生变化时,添加一致性用例。运行期回归可加入编译器仓库的 tests/run,应拒绝的程序加入 tests/fail。具体格式见编译器贡献指南。
更新日志
本页记录 Puddi 0.1 系列的正式发布内容。后续主分支进展见上游更新日志。
0.1.2
发布于 2026-11-21。
标准库
- 新增 10 个便携模块,涵盖集合、惰性迭代、文本和格式化、二进制读取、编码、路径、CSV、日期时间和统计。
- JSON 增加指针查找和缩进输出,CSV 支持自定义分隔符,
std.fmt支持解析 2 至 36 进制整数。
修复
- 支持前向类型别名并诊断循环。常量中的名称在声明模块解析。
- 修复浮点字面量拓宽、闭包参数推断、特征实现方法中的关联类型,以及命名约定相关的诊断和解析。
- 拒绝重叠的特征实现、循环父特征、非法 UTF-8 和不合法的 JSON 代理对。
- WIT 导出支持接口声明的记录、变体、枚举和标志位。
pud fmt保留多行字符串里的尾随空白。
0.1.1
发布于 2026-11-21。本次更新改进了实现 0.1 语言规范草案的工具链。
修复
pud在解析--target=<值>时会拒绝未知或空的目标名,与--target <值>和-t <值>一致。见 PR #6。
性能
- 内置汇编器可并行组装生成的 WebAssembly 文本。编译器也可并行解析大文件并生成函数代码。
pud build和pud run会复用输入未变的构建产物。Wasmtime 按函数缓存机器码,修改源码后可复用未变函数的编译结果。- Wasmtime 使用复制式垃圾回收。新的 IR 优化器减少闭包和小函数调用开销,迭代器和标准库中的排序、映射等操作也减少了内存分配和重复工作。
文档
- 上线完整简体中文文档,覆盖语言指南、规范、工具链、互操作及标准库。
- 新增贡献指南、行为准则、安全策略、编译器架构与发布流程,以及尚未生效的治理草案。
0.1.0
发布于 2026-11-18。Puddi 和 pud 工具链的首个发行版,实现了 0.1 语言规范草案。
语言
- 结构体、枚举、元组、受约束的泛型、默认方法、关联类型、父特征、
dyn Trait、运算符特征和闭包 - 带穷尽性检查的模式匹配,以及
if let、while let和let ... else ?与From转换、Error特征和AnyErr@derive(Eq, Ord, Hash, Show, Transfer)、常量、类型别名、模块与导入async fn、.await、支持结构化取消的task.scope、工作线程- WIT 导入、
export fn、@extern、@export、@target、@deprecated与test块
工具链
pud new、build、run、test、check、fmt、doc和addbrowser、wasi(WASI 0.3)与plugin目标均生成基于 WasmGC 的组件pud run内嵌 Wasmtime- Git 依赖采用最小版本选择,并写入
pud.lock,也支持本地路径依赖
测试和分发
conformance/为规范性小节提供一致性用例- Linux、macOS 和 Windows 持续集成
- 提供 Linux 和 macOS 的 x86_64、arm64 产物,以及 Windows x64 产物和安装脚本
已知差异
命名警告、类型名小写的结构体字面量、混合浮点与无符号整数、关联类型、重复实现、未注明的闭包参数和部分 WIT 导出,详见一致性测试。
参与贡献
欢迎提交问题、一致性用例、编译器修复、标准库改进、示例和文档。可以用中文或英文交流。
| 仓库 | 内容 |
|---|---|
| puddi-lang/puddi | 语言规范、编译器、标准库、一致性测试 |
| puddi-lang/puddi-docs | 中英文文档站 |
编译器的贡献指南说明如何构建和测试。想了解实现可以先看编译器开发。
从哪里开始
- 挑选小任务:查看 good first issue,或到讨论区问一问
- 报告问题:附最小示例、
pud version、运行命令、实际结果和预期结果 - 修正规范差异:从已知差异选一个,对应用例会提示修复是否生效
- 改进文档:从页面上方的编辑入口开始;语义和示例改动请同步至
src/和src-zh-CN/对应页面
修改语言
修改规范性文字可能改变有效程序的范围或程序含义。先开 Issue 说明问题、拟议规则和对现有程序的影响。实施时应同时更新一致性用例。尚未实现的规则可用 xfail 标注差异。治理草案说明了计划中的 RFC 流程。
构建文档
git clone https://github.com/puddi-lang/puddi-docs
cd puddi-docs
tools/build.sh # build English and Simplified Chinese
python3 -m http.server --directory book 8000
node tools/check-examples.mjs # compile and run every example with pud
需要 mdBook 0.5、Node.js 22 或更新版本,以及 PUDDI_VERSION 中指定的 pud 发行版。CI 会检查声明 fn main 或 test 的 puddi 代码块;紧跟着的 text,output 块是运行预期。不能独立检查的示例用 puddi,ignore,预期拒绝的用 puddi,fail,浏览器示例用 puddi,browser。
贡献适用各仓库说明的 MIT 或 Apache 2.0 双许可证。
项目治理
Puddi 目前按小型开源项目的方式运作。puddi-lang 的维护者在 Issue 和 PR 中公开讨论变更并审查代码。
编译器仓库的治理草案尚未生效。它描述贡献者、审查者与维护者的角色、共识与表决流程、规范和标准库的 RFC、发布与稳定性政策、安全报告、行为准则的执行方式,以及草案生效的条件。
现阶段,重要变更先讨论再实现。修改规范性规则时同时提交一致性用例。
行为准则
所有参与者都应遵守项目行为准则。它适用于仓库、Issue、PR 及其他项目空间。
请尊重彼此,耐心交流,善意理解他人,礼貌地提出和接受技术批评。骚扰及其他滥用行为不被接受。完整准则说明了不可接受的行为、如何私下报告以及维护者如何处理相关报告。