Skip to content

Reason for deprecation: Language design decision of 2026-06-16—Lambda/function values do not implicitly capture outer variables; explicit parameter passing is used instead. spawn { } executes in the same frame and does not involve closure capture. This RFC's capture analysis system has been completely removed (~850 lines of code). The correct solution for context-dependent behavior = closures take only parameters + currying is fixed at the creation point (SPEC §12.3 / RFC-009 §2.3). See RFC-009 design decisions.

RFC-023: Closure Capture Model ​

References:

Summary ​

This RFC defines the closure capture model for the YaoXiang language. The compiler automatically analyzes the outer variables referenced by the closure body and, based on the variable type (Dup/non-Dup) and whether the closure escapes, automatically selects the capture mode—copying Dup types directly, borrowing non-Dup types when they do not escape, and moving non-Dup types when they do. Users need no annotations, and the model shares the same set of rules as the automatic borrow selection for function calls.

Motivation ​

Why Is It Needed? ​

Closure capture is currently an empty implementation—the env field of the MakeClosure instruction is always empty, so a lambda cannot reference any outer variables. The borrow-token system requires closures to capture &T tokens (zero-cost copies), which is a core use case.

Current Issues ​

yaoxiang
# This code currently cannot compile—the lambda cannot reference threshold
filter_by: (items: List(Point), threshold: &Float) -> List(Point) = {
    items.filter(|p| p.x > threshold)  # ❌ threshold cannot be captured
}

Proposal ​

Core Design ​

Closure capture is determined fully automatically by the compiler. The rules are exactly the same as the automatic borrow selection used for function calls:

变量类型闭包是否逃逸捕获方式
─────────────────────────────────────────
Dup         任意复制(比特拷贝或零成本)
非 Dup      不逃逸自动借用(&T 或 &mut T)
非 Dup      逃逸            Move(所有权转移)

Escape determination:

spawn { || ... }           → 逃逸
return || ...              → 逃逸
let x = || ... ;  x 存字段 → 逃逸
items.filter(|p| ...)      → 不逃逸(sync 高阶函数调用)
||.method()                → 不逃逸(当场调用)

Conservative principle: when it cannot be determined, treat the closure as escaping.

Examples ​

yaoxiang
# 1. Dup token—direct copy (zero cost)
filter_by: (items: List(Point), threshold: &Float) -> List(Point) = {
    # threshold: &Float → Dup → compiler copies the token into the closure
    # Zero-sized token, zero runtime overhead
    items.filter(|p| p.x > threshold)
}

# 2. Non-Dup + non-escaping—automatic borrow
process: (buf: Buffer) -> Void = {
    # buf is not Dup, filter does not escape → automatically creates an &Buffer token
    transform(|b| b.read())
    # After the closure returns, the token is released and buf is available again
}

# 3. Escaping closure—Move
spawn_worker: (data: Data) -> Void = {
    # data is not Dup, spawn → escapes → Move
    spawn { use(data) }
}

# 4. Mixed captures
complex: (items: List(Point), config: &Config, buf: Buffer) -> List(Point) = {
    # config: &Config → Dup → copy the token
    # buf: Buffer → not Dup, does not escape → &mut Buffer borrow
    items.filter(|p| {
        let threshold = config.get_threshold()
        buf.update(p)
        p.x > threshold
    })
}

# 5. Borrow conflict detection
bad: (buf: Buffer) -> Void = {
    closure = |b| b.write()
    buf.read()  # ❌ buf has already been borrowed by the closure; conflict here
}

Syntax Changes ​

No syntax changes. The capture mode is determined automatically by the compiler; users do not need to provide annotations.

Detailed Design ​

Type System Impact ​

The lambda's type signature remains unchanged: (params) -> Return. Captured variables do not appear in the type signature; the compiler handles them during IR generation.

Compiler Changes ​

ComponentChangesDescription
capture.rs (new)Capture analysis + escape analysis + mode selection~150 lines
expressions.rsLambda type inference invokes capture analysis~10 lines
ir_gen.rsPopulate MakeClosure env; skip ZSTs~80 lines
ir.rsThe MakeClosure env type may need adjustment~5 lines

Capture analysis flow:

1. 遍历 lambda body AST
2. 收集所有 Expr::Var(name) 引用
3. 过滤:只保留闭包外部作用域的变量
4. 分类:Read(只读)/ Write(读写)/ Move(被转移)
5. 查类型属性:是否 Dup
6. 判逃逸:闭包的使用方式
7. 选择捕获模式:
   Dup → Copy
   非Dup + 不逃逸 + Read → Borrow(&T)
   非Dup + 不逃逸 + Write → BorrowMut(&mut T)
   非Dup + 逃逸 → Move

IR generation:

rust
// Current (empty)
Instruction::MakeClosure { dst, func, env: Vec::new() }

// Change to
Instruction::MakeClosure { dst, func, env: captured_env }

// Logic for generating captured_env:
for captured in captures {
    match captured.mode {
        Copy if is_zst(captured.ty) => {
            // Zero-sized type—generate no instructions
            // The closure body directly references the outer variable (eliminated at compile time)
        }
        Copy => {
            // Generate Move dst, src (shallow copy of a Dup type)
        }
        Borrow => {
            // Generate Borrow dst, src (create a ReadToken)
        }
        BorrowMut => {
            // Generate Borrow dst, src (create a WriteToken)
        }
        Move => {
            // Generate Move dst, src (ownership transfer)
        }
    }
}

Runtime Behavior ​

The capture mode does not affect runtime performance:

  • Dup + ZST (such as &T tokens) → zero instructions; the closure body directly references the outer variable
  • Dup + non-ZST (such as Int) → one register copy
  • Borrow/BorrowMut → create a token (a compile-time concept, zero overhead)
  • Move → the same cost as a normal Move

Backward Compatibility ​

Fully compatible. Currently, no lambda can capture outer variables; this RFC only adds expressive power and does not break any existing code.

Trade-offs ​

Advantages ​

  1. Zero annotations: Users do not need to write any capture annotations
  2. Unified with function calls: Capture rules = the automatic borrow rules for function calls
  3. Zero cost: Capturing Dup tokens is completely eliminated at compile time
  4. Safety: Escape analysis prevents use-after-free

Drawbacks ​

  1. Conservative escape analysis: When it cannot be determined, the closure is treated as escaping, which may lead to unnecessary Moves
  2. Implicit: Capture modes are not represented in the code, so debugging requires inspecting compiler output

Alternatives ​

ApproachWhy It Was Not Chosen
Rust-style explicit move keywordIntroduces new syntax and increases the user's cognitive burden
Move everythingCannot express zero-cost token borrowing
Borrow everythingAn escaping closure would result in a dangling reference
Users manually annotate the capture modeContradicts the design philosophy of "fully automatic compiler operation"

Implementation Strategy ​

Phase Breakdown ​

  1. Phase 1: Capture analysis (identify external variable references only; do not distinguish capture modes)
  2. Phase 2: Escape analysis + mode selection
  3. Phase 3: IR generation + ZST optimization
  4. Phase 4: Integration of borrow conflict detection

Dependencies ​

  • Depends on RFC-011 (generic system, Section 2.4 Dup/Clone trait)—the Dup trait is needed to determine whether a variable is copyable
  • Depends on RFC-009 v9 (borrow tokens)—the Borrow/BorrowMut capture modes require token types
  • After RFC-023 and this RFC have been implemented, the borrow-token system (the RFC-009 v9 implementation) can get started

Risks ​

  • Escape analysis may be overly conservative, resulting in unnecessary Moves; this can be optimized later
  • Capture analysis for generic closures may require additional handling

Design Decision Record ​

DecisionResolutionRationaleDate
Capture mode selectionFully automaticUnifies with function-call rules2026-05-29
Escape analysisConservative principleTreat as escaping when uncertain; safety first2026-05-29
ZST optimizationSkip during IR generationSimpler than a later optimization pass2026-05-29
Capture not represented in the type signatureHandled internally by the compilerKeeps the lambda type concise2026-05-29

References ​

Official YaoXiang Documentation ​

External References ​