仓颉 stdx.effect 实战:用 `perform`/`resume` 编写即时效应处理器(Immediate Effect Handler)

原创2026-10-14 22:49:421,647 阅读
文章标签:标准库

仓颉 stdx.effect 实战:用 perform/resume 编写即时效应处理器(Immediate Effect Handler)

导读

本文以 cangjie_stdx 仓库中 stdx.effect 包的官方示例 simple_immediate_effect.md 为骨架,系统讲解仓颉(Cangjie)语言中 Effect Handlers(效应处理器)的核心用法:如何定义效应(Command)、如何用 perform 触发、如何用 handle 子句处理并通过 resume 恢复执行,以及如何捕获"效应未被处理"的 UnhandledCommandException。读完本文,你将能够独立编写可运行的即时效应处理器代码,并理解 stdx.effect 在源码层面的分发机制(perform 如何沿 handler 链匹配)。

前置说明:Effect Handlers 是仓颉的实验性功能,需要支持该机制的 Cangjie 编译器,并在编译时启用 --experimental 与 --enable-eh 两个编译选项。stdx.effect 包仅在 CANGJIE_BUILD_WITHOUT_EFFECT_HANDLERS 未定义时参与构建(见 src/stdx/CMakeLists.txt 与 README_zh.md 中关于 effect 模块"提供用于处理 Effect Handler 特性的用户级 API"的说明)。

一、示例全景:一个完整的即时效应处理器

官方示例 simple_immediate_effect.md 演示了最基础的效应处理闭环:定义两个效应类型(生成随机数 Random、发送消息 Send),在 try 块中依次触发它们,并用一个 handle 子句处理其中一个,同时用 catch 捕获"效应未被任何 handler 处理"时抛出的异常。

完整代码(摘自 simple_immediate_effect.md):

import stdx.effect.{Command, UnhandledCommandException}

// Define two effect types: generating a random number and sending a message
class Random <: Command<Int64> {}
class Send <: Command<Unit> {
    Send(let msg: String) {}
}

main() {
    try {
        // Perform the Random effect
        let x = perform Random()
        println("Got random number ${x}, sending...")

        // Perform the Send effect
        perform Send("Sending ${x}")
    } handle(_: Random) {
        // Handle the Random effect, immediately returning 42
        resume with 42
    } catch(_: UnhandledCommandException) {
        // If an effect is not handled (in this case, Send), this exception is thrown
        println("Attempting to perform an unhandled command")
    }
}

运行输出:

Got random number 42, sending...
Attempting to perform an unhandled command

这个 30 行的例子浓缩了 Effect Handlers 的全部核心语法元素,下面逐一拆解。

二、核心概念:效应(Effect)与命令(Command)

2.1 效应与异常的异同

Effect Handlers 是一种强大的非局部控制操作,最初在函数式编程语言中被引入用于表达副作用,随后被证明在面向对象和过程式语言中同样实用(参见 effect_package_overview.md)。

它与异常机制高度对称:异常通过 throw 抛出、catch 捕获;效应通过 perform 触发、handle 处理。关键区别在于恢复能力:异常被捕获时,触发异常的计算过程已经中止、无法恢复;而效应被处理时,handler 可以选择恢复触发该效应的计算过程,将控制权返回到 perform 执行点继续执行。这正是示例中 perform Random() 被 resume with 42 恢复后,println 仍能拿到 x(值为 42)并继续执行的原因。

2.2 Command<T>:效应的类型载体

所有效应都必须继承自 Command<T>,其中 T 是该效应被恢复执行时返回给 perform 表达式的类型。stdx.effect 包在源码中直接定义了该抽象类(见 effect.cj):

public abstract class Command<Res> {
    public open func defaultImpl(): Res {
        throw UnhandledCommandException()
    }
}

要点:

  • Command<Res> 是抽象类,Res 为效应执行结果的类型参数,对应 API 文档中的 Command\<Res\>(见 effect_package_classes.md)。
  • 抽象方法 defaultImpl() 提供默认处理逻辑:当效应没有被任何 handler 捕获时,该方法会被调用;基类默认实现直接抛出 UnhandledCommandException。
  • 子类可以重写 defaultImpl() 为效应提供"兜底行为"。示例中 Random 与 Send 都没有重写,因此未被 handler 处理时会走默认抛异常路径。

示例中两个效应的定义方式:

class Random <: Command<Int64> {}   // 恢复后返回 Int64
class Send <: Command<Unit> {       // 恢复后返回 Unit
    Send(let msg: String) {}
}

Random 是空类,仅声明"我要一个 Int64 结果";Send 携带一个 msg 字段,体现"效应对象本身可以携带数据"的设计——handler 可以通过参数绑定的效应对象访问这些数据。

2.3 perform 表达式:触发效应

perform expr 触发一个效应,其中 expr 必须是某个 Command<T> 的实例。若被 handler 恢复,perform 表达式的类型为 T。类型规则如下(来自 effect_package_overview.md):

  • perform expr 的类型是 Command<T> 中的 T;
  • handle 捕获的类型必须是 Command 的子类;
  • resume with value 中 value 的类型必须与 T 一致;
  • resume throwing exn 中 exn 必须是 Exception 或 Error 的子类型。

2.4 handle 子句与 resume 表达式:处理与恢复

handle 子句定义效应被触发时的处理逻辑,语法上是对传统 try-catch 结构的扩展:一个 try 表达式除了 catch 块外,还可以包含一个或多个 handle 块。运行时匹配最近的 handle 子句并进入处理代码块;在 handle 中必须通过 resume 表达式恢复执行。通用语法:

try {
    ...
} handle (cmd: Command<T>) {
    // handler logic
    resume with value
}
  • cmd 绑定到被触发的效应对象(不需要该对象时可写作 _,如示例中的 handle(_: Random));
  • resume with value 将执行流程恢复到 perform 处,并以 value 作为该 perform 表达式的求值结果;
  • resume throwing exn 则把异常抛回 perform 执行点。

三、示例逐步拆解:恢复、未处理与异常捕获

3.1 第 1 步:Random 效应被恢复

程序进入 try 块,执行到 let x = perform Random() 时触发 Random 效应。运行时沿当前作用域的 handler 链查找,命中 handle(_: Random) 子句,进入处理块并执行 resume with 42。控制权返回 perform 处,Random() 表达式的值为 42,赋给 x,随后打印:

Got random number 42, sending...

注意:这里 42 是 handler 硬编码的返回值,与"随机数"名称无关——这正体现了效应处理器把"做什么"(效应声明)与"怎么做"(handler 实现)解耦的能力。

3.2 第 2 步:Send 效应未被处理,触发 UnhandledCommandException

继续执行到 perform Send("Sending ${x}") 时,再次触发效应。由于示例中只注册了一个 handle(_: Random) 子句,没有能匹配 Send 的 handler,运行时只能调用 Send 的默认实现 defaultImpl()——而 Send 没有重写该方法,于是基类实现抛出 UnhandledCommandException(见 effect.cj 与 effect_package_exceptions.md)。

该异常被紧随其后的 catch(_: UnhandledCommandException) 捕获,打印:

Attempting to perform an unhandled command

UnhandledCommandException 的默认消息为 "Unhandled command: no enclosing handler handles this command.",它作为一种运行时安全机制,提示开发者必须为效应提供明确的处理逻辑(源码见 effect.cj)。

3.3 运行全流程小结

  1. perform Random() 触发效应 → 匹配 handle(_: Random) → resume with 42 → 回到 perform 处,结果为 42;
  2. perform Send(...) 触发效应 → 无匹配 handler → 调用默认 defaultImpl() → 抛出 UnhandledCommandException → 被 catch 捕获并打印提示。

四、深入 stdx.effect 源码:perform 的匹配与分发机制

了解了语法层,再看源码层 stdx.effect 是如何实现"沿最近 handler 链匹配"的。包内实现集中在三个文件(见 effect/CMakeLists.txt):

  • effect.cj:公开 API——Command<Res> 抽象类与两个异常类;
  • common.cj:核心分发逻辑 HandlerFrame.perf,以及 FrameBox、HandlerCase、HandlerFrame 等内部结构;
  • immediate.cj:即时(immediate)处理器框架,包括 ImmediateHandlerCase、ImmediateFrame 及内部用于提前退出的包装类。

4.1 活跃 handler 帧的线程局部存储

HandlerFrame 使用 ThreadLocal<FrameBox>(键为 ACTIVE_FRAME_KEY)维护当前线程活跃的 handler 帧,FrameBox.ref 指向当前帧,帧之间通过 parent 指针串成链(见 common.cj)。每次进入 try-handle 结构,ImmediateFrame.start() 会把当前帧压栈,并在 finally 中恢复上一帧并执行 finalizer(见 immediate.cj)。

4.2 perf:沿帧链逐个尝试 handler

perform expr 在编译器脱糖(desugar)后最终调用 HandlerFrame.perf。其核心逻辑(见 common.cj)为:

public static func perf<Cmd, Res>(cmd: Cmd): Res where Cmd <: Command<Res> {
    let mainBox = getActiveFrameBox()
    var maybeFrame = getActiveFrame()
    while (let Some(frame) <- maybeFrame) {
        for (i in 0..frame.handlers.size) {
            if (let Some(result) <- frame.handlers[i].tryHandle(cmd, box: mainBox)) {
                return result
            }
        }
        maybeFrame = frame.parent
    }
    cmd.defaultImpl()
}

可以看到:

  1. 从当前活跃帧开始,依次尝试该帧注册的每个 HandlerCase(tryHandle);
  2. 当前帧全部未命中时,沿 parent 指针向外层帧继续查找——这就是"匹配最近的 handle 子句"的源码实现;
  3. 若整条链都没有 handler 命中,最终调用 cmd.defaultImpl(),即触发默认行为(默认抛 UnhandledCommandException)。

ImmediateHandlerCase.tryHandle 负责把命令对象做类型匹配(maybeCmd as Cmd),命中后执行用户 handler 函数,并依据 ImmediateHandlerReturn 的三种形态分发结果:Result(v) 正常恢复、Exc(e) 抛异常、Err(e) 抛错误(见 common.cj 与 immediate.cj)。

从源码结构可以推断:stdx.effect 内置的处理器属于即时(immediate)处理器——handler 直接在 perform 调用栈上同步执行并立刻恢复,因此示例标题中的 "Immediate" 指的就是这类同步、即刻返回的效应处理方式。

五、进阶用法:默认实现、恢复抛异常与嵌套 handler

除了示例中的基础形态,官方概览文档(effect_package_overview.md)还给出了三种进阶用法,均可在示例基础上直接组合使用。

5.1 重写 defaultImpl:为效应提供兜底行为

若希望效应在"没有 handler"时也能正常完成,而非抛异常,可重写 defaultImpl:

import stdx.effect.Command

class Print <: Command<Unit> {
    Print (let msg: String) {}
    override func defaultImpl(): Unit {
        println(msg)
    }
}

main() {
    perform Print("No handler here") // Calls the default implementation
}

输出:

No handler here

Print 未被任何 handler 捕获,但因为重写了 defaultImpl,程序正常打印消息。这也印证了源码中 perf 的最后一步 cmd.defaultImpl() 的设计:默认实现是"无人处理"时的统一出口。

5.2 resume throwing:从 handler 向 perform 处抛回异常

handler 中不仅可以用 resume with value 返回值,还可以用 resume throwing exn 把异常抛回 perform 执行点,由外层 catch 捕获:

import stdx.effect.Command

class Eff <: Command<Unit> {}

main() {
    try {
        perform Eff()
    } handle (e: Eff) {
        resume throwing Exception("Error from effect")
    } catch (exn: Exception) {
        println(exn.message)
    }
}

输出:

Error from effect

注意此时 resume throwing 抛出的异常是从 perform 处继续向上传播的,因此可以被 try 结构外层的 catch (exn: Exception) 捕获——这是效应恢复机制与异常机制协同的典型场景。

5.3 嵌套 handler 与"深度计数":恢复后的再次触发

官方 API 文档 effect_package_classes.md 提供了一个精彩的嵌套示例:定义 GetDepth 效应,默认实现返回 0(表示"没有显式 handler 时深度为 0"),而每个 deeper 函数安装的 handler 会重新触发 GetDepth 效应并把深度加 1:

import stdx.effect.*

public class GetDepth <: Command<Int64> {
    public func defaultImpl(): Int64 {
        0
    }
}

func deeper<T>(f: () -> T): Unit {
    try {
        f()
    } handle(e: GetDepth) {
        resume with ((perform e) + 1)
    }
}

main() {
    println("Depth: ${perform GetDepth()}")
    deeper {
        println("Depth: ${perform GetDepth()}")
        deeper {
            println("Depth: ${perform GetDepth()}")
        }
        println("Depth: ${perform GetDepth()}")
    }
    println("Depth: ${perform GetDepth()}")
}

输出:

Depth: 0
Depth: 1
Depth: 2
Depth: 1
Depth: 0

这个例子揭示了两个关键机制:

  • resume with ((perform e) + 1):handler 内部可以再次 perform 同一个效应对象 e,此时控制权会跳到外层的 handler(因为当前 handler 尚未恢复、正在处理中),从而形成"递归式"的深度计数;
  • defaultImpl 返回 0 保证了程序永不抛 UnhandledCommandException——文档指出,这等价于把 main 的整个函数体包在 try { ... } handle(_: GetDepth) { resume with 0 } 中。

从源码 perf 的帧链遍历逻辑(common.cj)可以印证:deeper 每进入一层就压入一个新帧,perform 总是优先匹配最近的帧;当前帧的 handler 若再次 perform,则继续向外层帧查找。

5.4 相关异常:DoubleResumeException

除了 UnhandledCommandException,包内还定义了 DoubleResumeException(见 effect_package_exceptions.md):当对同一个效应尝试多次 resume 时抛出。效应处理器的语义要求每个 Resumption 最多被恢复一次,以防止程序状态不一致或行为不可预测。该异常的默认消息为 "Cannot resume: resumption has already been resumed."(源码见 effect.cj)。

六、编译与工具链注意事项

由于 Effect Handlers 是实验性特性,使用时有明确的编译与工具链约束(见 effect_package_overview.md 末尾的说明):

  • 需要支持 Effect Handlers 机制的 Cangjie 编译器;
  • 编译带 Effect Handlers 的代码时必须启用编译选项 --experimental 和 --enable-eh;
  • 工具支持现状如下表:
工具 支持情况
Cjdb 已可正常使用
LSP 暂不识别与 Effect Handlers 相关的关键字
Formatter 尚未支持
Coverage 尚未支持
Cjlint 尚未支持

此外,从构建系统看,effect 目录的编译受 CANGJIE_BUILD_WITHOUT_EFFECT_HANDLERS 开关控制:只有该宏未定义时才 add_subdirectory(effect)(见 src/stdx/CMakeLists.txt),build.py 亦提供了 --without-effect-handlers 参数来控制该宏(见 build.py)。这说明在关闭 Effect Handlers 特性的构建产物中不会包含 stdx.effect 包,使用前需确认所用 stdx 构建是否启用了该模块。

七、小结:从示例到生产可用的要点清单

回到开篇的示例,它覆盖了 Effect Handlers 最核心的完整闭环。作为收束,给出编写即时效应处理器时的要点清单:

  1. 效应即命令:所有效应类必须继承 Command<T>,T 决定 perform 表达式与 resume with value 的类型;
  2. 触发用 perform:perform expr 遇到最近的匹配 handle 子句时交出控制权,被 resume 后从原处继续;
  3. 处理用 handle:一个 try 可挂多个 handle 子句,运行时沿 handler 帧链(见 common.cj)由近及远匹配;
  4. 恢复用 resume:resume with value 返回结果、resume throwing exn 抛回异常,且同一效应最多恢复一次;
  5. 兜底用 defaultImpl:不重写时默认抛 UnhandledCommandException,重写后可为无人处理的效应提供行为;
  6. 编译两选项:--experimental --enable-eh,并确认所用 stdx 构建包含 effect 模块。

这套机制把"效应的声明"与"效应的处理"彻底分离,既可用于依赖注入式的能力抽象(如示例中的随机数生成、消息发送),也可用于构建嵌套的、可组合的控制流(如深度计数示例)。建议读者在掌握本文示例后,进一步阅读 effect_package_overview.md 与 effect_package_api 目录下的类与异常文档,并对照 src/stdx/effect 源码理解帧链分发细节。

登录后查看全文
cangjie_stdx