Skip to content

RFC-032: Unified spawn Expression Modifier ​

This document defines the syntax of spawn and the corresponding AST/IR refactoring. Runtime behavioral semantics (task decomposition granularity, ownership, scope, error propagation, resource types, and nesting) are covered in RFC-024: Concurrency Model Based on spawn.

Two RFCs work together to define spawn—024 answers "what to do," while 032 answers "how to represent it."

Core insight: spawn should not modify only {} blocks. It can modify any expression. spawn for is not special syntax—it is the natural combination of spawn and a for expression.

Summary ​

Extend spawn from spawn { } (which modifies only blocks) to spawn <expr> (which modifies any expression). Expr::SpawnFor is removed from the AST and naturally replaced by Expr::Spawn { body: Expr::For { .. } }. This RFC only performs AST/IR/Parser cleanup and does not involve any type-system changes.

Computational structure types (the MonoType extension) are deferred to a separate RFC. After this RFC removes the SpawnFor special case, integrating spawn into the proof pipeline requires type-system-aware computational structures—a general mechanism that is not limited to spawn and warrants an independent design.

Motivation ​

Why is this change needed? ​

The current spawn for x in items { body } is a separate keyword combination, with a dedicated Expr::SpawnFor variant in the AST. This breaks the orthogonality of the language:

  1. Inconsistent syntax: spawn can modify only {} blocks, while spawn for is a hard-coded exception
  2. Lack of orthogonality: combinations such as spawn while and spawn if cannot be expressed naturally

Current problem ​

rust
// Two spawn variants in the AST
Spawn { body: Box<Block>, span: Span },         // spawn { ... }
SpawnFor { var, var_mut, iterable, body, span },  // spawn for x in items { ... }

Proposal ​

Core design ​

spawn <expr>: spawn modifies any expression. The expression's shape determines how the DAG decomposes the work into tasks.

User mental model ​

spawn means "take this expression and run it concurrently." The expression's shape determines how it is split up:

Expression shapeConcurrency behavior
spawn { a, b, c }a, b, and c run independently in parallel
spawn for x in items { f(x) }N iterations run independently in parallel
spawn while cond { step() }Each iteration is an independent task
spawn if c { a } else { b }The selected branch as a whole is the spawn domain
spawn call(x)The call itself is one task
spawn 42A single task

The compiler performs DAG analysis to determine dependencies. At runtime, tasks are scheduled according to the GMP model—independent tasks are placed in a work queue, where workers compete to run them. The operation as a whole blocks synchronously until all tasks have completed.

Difference from Go: Go's go is "fire and forget," whereas YaoXiang's spawn means "split it for parallel execution, wait for everything to finish, and then continue."

Control-flow orthogonality ​

FormSemanticsDifference
spawn for x in items { body }Data parallelism: each iteration = one taskThe DAG analyzes dependencies across iterations
for x in items spawn { body }Each iteration creates a spawn domainNo cross-iteration analysis
spawn while cond { body }Conditional parallelism: each iteration = one taskDependencies between iterations are guaranteed by the condition
while cond spawn { body }Each iteration creates a spawn domainSemantics differ from the above, but no special handling is needed
spawn if c { a } else { b }The entire if-else is one spawn domainThe branch is selected at runtime based on the condition
if c spawn { a } else { b }Only one branch is spawnedspawn is wrapped inside the if expression

Eliminated complexity ​

  • ❌ Expr::SpawnFor is removed from the AST
  • ❌ SpawnForAnalysis is removed from DAG analysis
  • ❌ spawn for is no longer specially handled in the Parser as a combined keyword
  • ❌ ir_gen's separate lowering path generate_spawn_for_expr_ir is removed (merged into the unified Spawn translation path)

Detailed Design ​

1. AST layer ​

Before:

rust
Spawn { body: Box<Block>, span: Span },         // spawn { ... }
SpawnFor { var, var_mut, iterable, body, span },  // spawn for x in items { ... }

After:

rust
Spawn { body: Box<Expr>, span: Span },           // spawn <any expression>

Expr::SpawnFor is removed. The AST representation of spawn for x in items { body } is:

rust
Expr::Spawn {
    body: Box::new(Expr::For {
        var: "x",
        iterable: items,
        body: body_block,
        ..
    })
}

IF special case:

FormAST structure
spawn if cond { a } else { b }Spawn { body: Expr::If { ... } }
if cond spawn { a } else { b }Expr::If { then: Spawn { body: {a} }, else: {b} }

Although the two have different semantics, both are natural compositions and require no special rules.

2. Parser layer ​

spawn has the lowest binding precedence (equivalent to return) and consumes the entire following expression:

spawn a + b        →  spawn (a + b)         ≠  (spawn a) + b
spawn f(x).y       →  spawn (f(x).y)

Parser change: in pratt/nud.rs, spawn no longer requires {; instead, it invokes general expression parsing:

token spawn → parse_expr(min_precedence) → Expr::Spawn { body: expr }

spawn for is no longer processed as a combined keyword—for is handled by the general expression parser, which produces Expr::For, and spawn is solely responsible for wrapping it.

3. DAG analysis layer ​

The two current entry points are merged into one:

rust
/// Unified entry point: dispatch based on the kind of body expression
fn analyze_spawn_expr(body: &Expr, ...) -> SpawnAnalysis {
    match body {
        Expr::Block(block)       => analyze_block_tasks(block, ...),
        Expr::For { .. }         => analyze_iter_tasks(IterKind::For, body, ...),
        Expr::While { .. }       => analyze_iter_tasks(IterKind::While, body, ...),
        Expr::If { .. }          => analyze_if_task(body, ...),
        _                        => single_task(body, ...),
    }
}

Unified result structure:

rust
struct SpawnAnalysis {
    source: TaskSource,
    plan: ExecutionPlan,
}

enum TaskSource {
    /// spawn { a, b, c } — N direct child expressions known at compile time
    Explicit(Vec<TaskInfo>),
    /// spawn for/while — N tasks generated by runtime iteration
    Iterate {
        kind: IterKind,
        iter_var: String,
        iterable: Option<Expr>,      // present with for, absent with while
        condition: Option<Expr>,     // present with while, absent with for
        body: Block,
        reads: HashSet<String>,
        writes: HashSet<String>,
        resource_vars: HashSet<String>,
    },
}

enum IterKind { For, While }

The SpawnForAnalysis struct is removed.

Body kindHow it is decomposed into tasks
Expr::BlockDirect child expressions → task list
Expr::ForEach iteration → one task (data parallelism)
Expr::WhileEach iteration → one task
Expr::IfThe selected branch as a whole → one task
Expr::Call / otherThe expression itself → one task

Once DAG analysis is complete, the runtime schedules tasks according to the GMP model—independent tasks are placed in a work queue, where workers compete to run them.

4. IR / Codegen layer ​

Fact correction (2026-10-14): The IR instruction layer (middle/core/ir.rs) never had a SpawnFor variant; it only has Instruction::Spawn(:330) and Instruction::SpawnFromList(:340), and both remain unchanged. The dual paths exist in the ir_gen translation layer: Expr::SpawnFor → generate_spawn_for_expr_ir(:8605) and Expr::Spawn → generate_spawn_expr_ir(:8624). This RFC merges the two translation paths and uniformly dispatches based on SpawnAnalysis.source to generate the Instruction::Spawn family.

HIR → IR translation generates runtime calls according to SpawnAnalysis.source:

  • TaskSource::Explicit(tasks) → a task list known at compile time
  • TaskSource::Iterate { .. } → runtime expansion (compiler-driven, similar to par_iter but with zero cost)

5. Placement layer ​

The two current branches are merged into one:

rust
// Before
Expr::Spawn { body, .. } => self.check_block(body),
Expr::SpawnFor { body, iterable, .. } => {
    self.check_expr(iterable);
    self.check_block(body);
}

// After
Expr::Spawn { body, .. } => self.check_expr(body),   // body is an Expr; recursion is sufficient

6. Backward compatibility ​

Existing spawn for code retains its semantics. The Parser automatically parses spawn for x in items { body } as Expr::Spawn { body: Expr::For }. The internal representation changes, but user-visible behavior does not.

The new syntax naturally supports:

yx
spawn while has_next() {
    item = next()
    process(item)
}

spawn if use_cache {
    load_from_cache(key)
} else {
    fetch(key)
}

Single-task spawn warning: When spawn modifies a single expression, such as spawn call(x) or spawn 42, DAG analysis emits a compiler warning: "spawn modifying a single expression has no concurrency effect." The syntax is legal, but the warning reminds users to verify their intent.

Trade-offs ​

Advantages ​

  1. Orthogonal syntax: spawn + arbitrary control flow = a natural concurrent composition
  2. Elimination of special cases: Removes Expr::SpawnFor and the related special-case code
  3. Extensibility: Future control-flow structures automatically compose with spawn, without requiring changes to the spawn logic

Disadvantages ​

  1. Breaking change: The internal AST representation changes, requiring updates to all 13 source files that consume Expr::SpawnFor (see "Scope of Impact"); IR snapshots must be regenerated in the same commit
  2. Proof-pipeline adaptation: After SpawnFor is removed, the proof pipeline dispatches through the AST (match body { Expr::For => ..., Expr::While => ... })—this adaptation is handled within the scope of this RFC through the unified DAG entry point

Alternatives ​

AlternativeWhy it was not selected
Keep spawn for as standalone syntaxBreaks orthogonality and becomes the language's only keyword-combination special case
Restrict spawn to {} and use the standard library's par_iter for data parallelismPushes a primitive language capability down into the library, losing compiler-level DAG analysis and resource-conflict detection

Computational Structure Types (Deferred to a Separate RFC) ​

After this RFC removes SpawnFor, integrating spawn into the proof pipeline presents an architectural challenge: the proof pipeline operates at the type layer and must know the computational structure inside spawn (For/While/Block/If/Call) to select the correct proof strategy. The proof pipeline currently dispatches through the AST, but the long-term direction is to encode computational structures as MonoType variants (Block/ForExpr/WhileExpr/IfExpr/Call/Spawn), allowing the pipeline to operate entirely at the type layer.

This is a weakened, practical version of RFC-019: Typed Homoiconicity—the compiler's built-in computational structures enter the type system, but user-defined syntax is not exposed. Its theoretical foundation is ECMTT (Contextual Modal Types for Algebraic Effects and Handlers, ICFP 2021): Spawn<T> corresponds to the modal operator □, and the proof pipeline corresponds to the handler.

This mechanism is not limited to spawn—future effects (pure computation, IO, and fallible operations) can all enter the type system through the same pattern. spawn is the first consumer, not the only consumer.

The separate RFC will define: the complete semantics of the 6 MonoType variants, the type-checker adaptation strategy, the unified interface for dispatching the proof pipeline by type, and the integration plan with RFC-027.

Implementation Strategy ​

Phase breakdown ​

  1. AST + Parser: Spawn { body: Box<Expr> }; remove SpawnFor
  2. Unified DAG analysis: Merge the entry points and unify the TaskSource enum. Single-task spawn (spawn call(x), spawn 42) produces a compiler warning
  3. IR / Codegen adaptation: Remove Ir::SpawnFor and unify the handling path
  4. Placement simplification: Remove the SpawnFor branch
  5. Test validation: All existing spawn for tests pass

Scope of Impact ​

File/directoryChanges
frontend/core/parser/ast.rsChange the Spawn body to Box<Expr> and remove SpawnFor (79/:1070)
frontend/core/parser/pratt/nud.rsRemove parse_spawn_for (154); change spawn to general expression parsing
frontend/core/parser/pratt/mod.rsRemove the SpawnFor branch from the span helper (52)
frontend/core/spawn/analysis.rsUnify the entry point; remove SpawnForAnalysis (46) and merge TaskSource
frontend/core/spawn/placement.rsRemove the SpawnFor branch (218)
frontend/core/typecheck/checker.rsMerge the For | SpawnFor arm into a single For (4812)
frontend/core/typecheck/passes/dead_code.rsRemove the SpawnFor branch (325)
frontend/core/typecheck/inference/expressions.rsRemove the SpawnFor branch (3950)
frontend/core/typecheck/inference/existential.rsRemove the SpawnFor branch from the span helper (60)
frontend/core/typecheck/layers/ownership.rsRemove the SpawnFor branches (1271, :2291)
frontend/core/typecheck/layers/termination.rsMerge the For | SpawnFor arm into a single For (1994)
middle/core/ir_gen.rsMerge generate_spawn_for_expr_ir (8605); remove the :4638/:5418 branches
middle/core/ir.rsUnchanged—the instruction layer never had SpawnFor; retain Spawn(:330)/SpawnFromList(:340)
formatter/handlers/expr.rsRemove the SpawnFor formatting branch (186); compose spawn for from Spawn+For
tests/yaoxiang/04-concurrency/spawn_for.yxSemantics remain unchanged; validation passes
IR snapshots src/middle/core/tests/snapshots/Related expression IR shapes change; regenerate in the same commit (AGENTS.md red-line requirement)

Dependencies ​

  • RFC-024 (spawn block concurrency model)—This RFC is its orthogonality extension
  • RFC-010 (unified type syntax)—The foundation for syntactic unification

Design Decision Record ​

DecisionResolutionRationaleDate
spawn modifier scopeAny expressionEliminates the spawn for special case2026-06-16
spawn while supportSupportedOrthogonal syntax with low implementation cost. The proof pipeline may reject use cases with cross-iteration dependencies.2026-06-16
spawn if semanticsModifies the entire if-elseDistinguishes it from if spawn { }2026-06-16
spawn binding precedenceLowest (equivalent to return)Consumes the entire following expression2026-06-16
DAG handling of for internalsDo not expand child expressions inside forThe direct-child expression rule remains unchanged; the for expression as a whole is one task source2026-06-16
Single-task spawn warningspawn call(x) / spawn 42 produce a compiler warningNo concurrency effect; reminds users to verify their intent2026-08-19
Computational structure typesDeferred to a separate RFCA general mechanism that is not limited to spawn. ECMTT provides the theoretical foundation2026-08-19
IR-layer fact correctionThe instruction layer has no SpawnFor; the merged paths are in the ir_gen translation layerir.rs contains only Spawn/SpawnFromList; the original statement was incorrect2026-10-14

References ​


Lifecycle and Destination ​

StatusLocationDescription
Under Reviewdocs/design/rfc/review/Open for community discussion