RFC-032: Unified spawn Expression Modifier
This document defines the syntax of
spawnand 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:
spawnshould not modify only{}blocks. It can modify any expression.spawn foris not special syntax—it is the natural combination ofspawnand aforexpression.
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
MonoTypeextension) are deferred to a separate RFC. After this RFC removes theSpawnForspecial case, integratingspawninto 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:
- Inconsistent syntax:
spawncan modify only{}blocks, whilespawn foris a hard-coded exception - Lack of orthogonality: combinations such as
spawn whileandspawn ifcannot be expressed naturally
Current problem
// 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 shape | Concurrency 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 42 | A 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
| Form | Semantics | Difference |
|---|---|---|
spawn for x in items { body } | Data parallelism: each iteration = one task | The DAG analyzes dependencies across iterations |
for x in items spawn { body } | Each iteration creates a spawn domain | No cross-iteration analysis |
spawn while cond { body } | Conditional parallelism: each iteration = one task | Dependencies between iterations are guaranteed by the condition |
while cond spawn { body } | Each iteration creates a spawn domain | Semantics differ from the above, but no special handling is needed |
spawn if c { a } else { b } | The entire if-else is one spawn domain | The branch is selected at runtime based on the condition |
if c spawn { a } else { b } | Only one branch is spawned | spawn is wrapped inside the if expression |
Eliminated complexity
- ❌
Expr::SpawnForis removed from the AST - ❌
SpawnForAnalysisis removed from DAG analysis - ❌
spawn foris no longer specially handled in the Parser as a combined keyword - ❌ ir_gen's separate lowering path
generate_spawn_for_expr_iris removed (merged into the unifiedSpawntranslation path)
Detailed Design
1. AST layer
Before:
Spawn { body: Box<Block>, span: Span }, // spawn { ... }
SpawnFor { var, var_mut, iterable, body, span }, // spawn for x in items { ... }After:
Spawn { body: Box<Expr>, span: Span }, // spawn <any expression>Expr::SpawnFor is removed. The AST representation of spawn for x in items { body } is:
Expr::Spawn {
body: Box::new(Expr::For {
var: "x",
iterable: items,
body: body_block,
..
})
}IF special case:
| Form | AST 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:
/// 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:
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 kind | How it is decomposed into tasks |
|---|---|
Expr::Block | Direct child expressions → task list |
Expr::For | Each iteration → one task (data parallelism) |
Expr::While | Each iteration → one task |
Expr::If | The selected branch as a whole → one task |
Expr::Call / other | The 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 timeTaskSource::Iterate { .. }→ runtime expansion (compiler-driven, similar to par_iter but with zero cost)
5. Placement layer
The two current branches are merged into one:
// 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 sufficient6. 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:
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
- Orthogonal syntax:
spawn+ arbitrary control flow = a natural concurrent composition - Elimination of special cases: Removes
Expr::SpawnForand the related special-case code - Extensibility: Future control-flow structures automatically compose with
spawn, without requiring changes to the spawn logic
Disadvantages
- 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 - Proof-pipeline adaptation: After
SpawnForis 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
| Alternative | Why it was not selected |
|---|---|
Keep spawn for as standalone syntax | Breaks orthogonality and becomes the language's only keyword-combination special case |
Restrict spawn to {} and use the standard library's par_iter for data parallelism | Pushes 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
- AST + Parser:
Spawn { body: Box<Expr> }; removeSpawnFor - Unified DAG analysis: Merge the entry points and unify the
TaskSourceenum. Single-task spawn (spawn call(x),spawn 42) produces a compiler warning - IR / Codegen adaptation: Remove
Ir::SpawnForand unify the handling path - Placement simplification: Remove the
SpawnForbranch - Test validation: All existing
spawn fortests pass
Scope of Impact
| File/directory | Changes |
|---|---|
frontend/core/parser/ast.rs | Change the Spawn body to Box<Expr> and remove SpawnFor (79/:1070) |
frontend/core/parser/pratt/nud.rs | Remove parse_spawn_for (154); change spawn to general expression parsing |
frontend/core/parser/pratt/mod.rs | Remove the SpawnFor branch from the span helper (52) |
frontend/core/spawn/analysis.rs | Unify the entry point; remove SpawnForAnalysis (46) and merge TaskSource |
frontend/core/spawn/placement.rs | Remove the SpawnFor branch (218) |
frontend/core/typecheck/checker.rs | Merge the For | SpawnFor arm into a single For (4812) |
frontend/core/typecheck/passes/dead_code.rs | Remove the SpawnFor branch (325) |
frontend/core/typecheck/inference/expressions.rs | Remove the SpawnFor branch (3950) |
frontend/core/typecheck/inference/existential.rs | Remove the SpawnFor branch from the span helper (60) |
frontend/core/typecheck/layers/ownership.rs | Remove the SpawnFor branches (1271, :2291) |
frontend/core/typecheck/layers/termination.rs | Merge the For | SpawnFor arm into a single For (1994) |
middle/core/ir_gen.rs | Merge generate_spawn_for_expr_ir (8605); remove the :4638/:5418 branches |
middle/core/ir.rs | Unchanged—the instruction layer never had SpawnFor; retain Spawn(:330)/SpawnFromList(:340) |
formatter/handlers/expr.rs | Remove the SpawnFor formatting branch (186); compose spawn for from Spawn+For |
tests/yaoxiang/04-concurrency/spawn_for.yx | Semantics 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
| Decision | Resolution | Rationale | Date |
|---|---|---|---|
| spawn modifier scope | Any expression | Eliminates the spawn for special case | 2026-06-16 |
spawn while support | Supported | Orthogonal syntax with low implementation cost. The proof pipeline may reject use cases with cross-iteration dependencies. | 2026-06-16 |
spawn if semantics | Modifies the entire if-else | Distinguishes it from if spawn { } | 2026-06-16 |
| spawn binding precedence | Lowest (equivalent to return) | Consumes the entire following expression | 2026-06-16 |
| DAG handling of for internals | Do not expand child expressions inside for | The direct-child expression rule remains unchanged; the for expression as a whole is one task source | 2026-06-16 |
| Single-task spawn warning | spawn call(x) / spawn 42 produce a compiler warning | No concurrency effect; reminds users to verify their intent | 2026-08-19 |
| Computational structure types | Deferred to a separate RFC | A general mechanism that is not limited to spawn. ECMTT provides the theoretical foundation | 2026-08-19 |
| IR-layer fact correction | The instruction layer has no SpawnFor; the merged paths are in the ir_gen translation layer | ir.rs contains only Spawn/SpawnFromList; the original statement was incorrect | 2026-10-14 |
References
- RFC-024: Concurrency Model Based on spawn Blocks
- RFC-010: Unified Type Syntax
- ECMTT: Contextual Modal Types for Algebraic Effects and Handlers (ICFP 2021) — The theoretical foundation for computational structure types
- Concurrency Model Specification
Lifecycle and Destination
| Status | Location | Description |
|---|---|---|
| Under Review | docs/design/rfc/review/ | Open for community discussion |
