RFC-009: Ownership Model Design
Abstract
This document defines the ownership model (Ownership Model) of the YaoXiang programming language.
Core design—five concepts, one gradient:
看一眼/原地改拿走共享持有复制一份系统级
│ │ │ │ │
&T Move ref clone() unsafe
&mut T 零拷贝编译器自动显式深拷贝 *T
零大小令牌默认选Rc/Arc 用户负责
类型属性自然
推导权限- Move (default): Assignment/argument passing/return = ownership transfer, zero-copy, with automatic RAII release
&T/&mut T(borrow tokens): Zero-sized compile-time token types.&Tis copyable (shared and read-only), while&mut Tis linear (exclusive and mutable). Permissions are inferred naturally from type attributes, with no special rules. Tokens may be returned and stored in structs.refkeyword: Sharing across scopes. The compiler automatically selects Rc (when not crossing tasks) or Arc (when crossing tasks)clone(): Explicit deep copyunsafe+*T: Raw pointers, a system-level escape hatch
Complexity eliminated:
- ❌ No lifetime
'a - ❌ No separate borrow-checking framework (borrow conflicts are reduced to Hoare propositions and share a proof pipeline with type checking)
- ❌ No GC
- ❌ No special rules such as "escape prohibition" (tokens are ordinary types, and their scopes are handled uniformly by the type system)
- ❌ Users do not need to know the difference between Rc and Arc (the compiler selects automatically)
Programming burden:
&Tis copyable, while&mut Tis not—two type attributes, zero special rules, and full compiler automation. Performance guarantees: Move has zero overhead, tokens have zero overhead (zero-sized types disappear after compilation), ref is pay-as-needed, and there are no GC pauses.
Integration with quantifiers: Move/Dup/Clone are the syntactic face of 1 (linear) and ω (free) in the binding quantifier
q ∈ {0, 1, ω}, and clone() explicitly crosses the quantifier. q=0 (zero quantification: compile-time computation and runtime erasure) is driven by the strength declarations in RFC-011 §4.1 and follows the same binding discipline as 1/ω in this model—ownership and compile-time-ness are three readings of the same rule.
Motivation
Why Is an Ownership Model Needed?
| Language | Memory Management | Problem |
|---|---|---|
| C/C++ | Manual management | Memory leaks, dangling pointers, double frees |
| Java/Python | GC | Latency fluctuations, memory overhead, unpredictable pauses |
| Rust | Ownership + borrow checks | Steep learning curve for lifetime 'a |
| YaoXiang | Move + Token + ref | Simple, deterministic, no GC |
Design Goals
# 1. Move by default (zero-copy)
p = Point(1.0, 2.0)
p2 = p # Move; p can no longer be read
# 2. &T / &mut T borrow tokens (zero overhead; permissions are inferred naturally from type attributes)
print_info(p2) # The compiler automatically creates an &Point token and releases it after use
shift(p2, 1.0, 1.0) # The compiler automatically creates an &mut Point token
# 3. ref = sharing (the compiler automatically selects Rc/Arc)
shared = ref p2 # Held across scopes
spawn { use(shared) } # Compiler: cross-task → Arc
# 4. clone() = explicit copy
backup = p2.clone() # Deep copy, independently owned
# 5. unsafe + *T = system-level
unsafe {
ptr: *Point = &p
(*ptr).x = 0.0
}Core Differences from Rust
| Feature | Rust | YaoXiang |
|---|---|---|
| Default semantics | Borrowing &T (requires explicit .clone()) | Move (value passing, zero-copy) |
| Borrowing | &T/&mut T, returnable, requires lifetimes | &T/&mut T zero-sized tokens; Dup/Linear type attributes naturally infer permissions |
| Sharing mechanism | Arc::new() + manual Weak | ref keyword (the compiler automatically selects Rc/Arc) |
| Copying | clone() | clone() |
| Raw pointers | *T | *T |
| Lifetime | 'a | ❌ None |
| Borrow checking | Global inference | The type checker automatically generates borrow propositions, which are validated by a unified proof pipeline |
| Cycles | Manual Weak | Unified release at task end / cross-task lint / standard-library Weak |
Proposal
1. Move (Default Ownership Transfer)
# Rule: assignment / argument passing / return = Move, zero-copy
p: Point = Point(1.0, 2.0)
p2 = p # Move; p can no longer be read
# Variables can be reassigned (Python style, no shadowing)
p = Point(3.0, 4.0) # p is rebound; the type must remain the same
# Function parameter: Move
process: (p: Point) -> Point = {
p.transform()
p # Move return
}
# Function return: Move
create: () -> Point = {
p = Point(1.0, 2.0)
p # Move return, zero-copy
}Characteristics:
- Zero-copy (the compiler moves a pointer)
- The original binding cannot be read after the move (compile error)
- RAII: automatically released when the scope ends
- The function signature
(T) -> Tis itself documentation—it consumes T and returns T
2. &T / &mut T (Borrow Tokens)
Core principle: &T and &mut T are zero-sized compile-time token types. They are not "references," but "type-level proofs of access permission."
2.1 Two Type Attributes
&T → 零大小,冻结源数据(ReadToken 存活期间禁止 WriteToken),
冻结保证下多份只读视图安全 → 可复制(Dup)
&mut T → 零大小,独占读写(WriteToken 存活期间禁止任何其他令牌),
独占访问下复制无意义 → 线性(非 Dup)Causality cannot be reversed: freezing is the cause, and Dup is the result. It is not that &T implements Dup and therefore can coexist—rather, because the data is frozen (mutation is impossible), multiple read-only views are safe, and only then can Dup be implemented. Treating Dup as the definition and conflict detection as an "additional patch" would be a design error.
2.2 Basic Usage
# Callee: declare parameter types to determine the required permissions
Point.print: (self: &Point) -> Void = {
print(self.x) # The &Point token grants read permission
print(self.y)
}
Point.shift: (self: &mut Point, dx: Float, dy: Float) -> Void = {
self.x = self.x + dx # The &mut Point token grants write permission
self.y = self.y + dy
}
# Caller: the compiler automatically chooses a borrow or Move
p = Point(1.0, 2.0)
p.print() # The compiler automatically creates an &Point token
p.shift(1.0, 1.0) # The compiler automatically creates an &mut Point token
p.print() # OK; the previous token was released when the shift call ended
# The same applies to free functions
distance: (a: &Point, b: &Point) -> Float = {
sqrt((a.x - b.x)**2 + (a.y - b.y)**2) # Two &Point tokens coexist—a Dup type
}
d = distance(p, p2)2.3 Why No "Escape Prohibition" Is Needed
RFC-009 v8 imposed three special rules on &T/&mut T: they could only be used as parameters, could not be returned, and could not be stored in structs. This was patching up the concept of "borrowing."
The token system needs none of these rules. Tokens are ordinary types and follow the same scope rules as every other type.
Returning references—naturally supported:
# ✅ The token propagates along with the return value
Point.get_x: (self: &Point) -> (&Float, &Point) = {
return (&self.x, self) # The child and parent tokens are returned together
}
# Usage
p = Point(1.0, 2.0)
(px_ref, p) = p.get_x() # The token is returned to the caller
print(px_ref) # OK; the token is still in scopeStoring tokens in structs—naturally supported:
# ✅ A struct carries a token as a field
Window: Type = {
target: Point,
view: &Point, # Token field—holds a read-only view of target
}
# The view token is derived from target, and Window owns both
# As long as Window exists, the view token remains valid2.3 Closures and Explicit Lambda Arguments
A Lambda is a function value—it can be returned, stored, and passed out of the current scope. Therefore, a Lambda does not implicitly capture outer local variables. When outer data is needed, pass it explicitly as an argument:
# ✅ Lambdas use explicit arguments
double: (x: Int) -> Int = (x) => x * 2
filter_by: (items: List(Int), f: (Int) -> Bool) -> List(Int) = { ... }
# ✅ spawn { } is not affected by this rule—spawn is a concurrent block that executes immediately, and the parent task blocks while waiting
shared = ref data
spawn { use(shared) }
# ❌ A Lambda cannot implicitly capture an outer variable
x = 42
f = () => { x + 1 } # Compile error: x is not in scope
# ✅ Correct approach: pass the argument explicitly
f = (x) => { x + 1 }
f(x)
# ✅ Correct approach two: fix the context at the creation point (currying)—the closure consumes only arguments and captures nothing
gt: (t: Int) -> (x: Int) -> Bool = (x) => x > t
evens = list.filter(nums, gt(threshold))Supplement (2026-08-17): The correct solution for context dependence is currying and fixation, not capture. After a closure escapes, the scope where it was defined may already be dead, so it must not implicitly capture; however, the call site (creation point) necessarily remains alive, and fixing the context there as a value before placing it in the closure is safe. See SPEC §12.3.
spawn { } is not a function value. A block marked with spawn, like an if/while body, executes immediately and completes while the parent stack frame is alive. A spawn body can access outer variables normally.
Cross-task—tokens cannot cross thread boundaries:
# ❌ Tokens cannot cross task boundaries
bad_task: (p: &Point) -> Void = {
spawn { print(p.x) } # ❌ Compile error: tokens cannot be passed across tasks
}
# This is not a special rule—tokens are compile-time permission proofs; use ref for cross-task sharing
# To share across tasks, use refTokens cannot be used with ref:
# ❌ A token is a permission proof, not ownership
bad_ref: (p: &Point) -> Void = {
shared = ref p # ❌ Compile error: &T is not an ownable type
}2.4 Token Lifetimes
Token lifetimes are determined by ordinary scope rules and do not require lifetime parameters:
- A token in a function parameter: lives for the duration of the call and is released when the call ends
- A returned token: ownership is transferred to the caller
- A token stored in a struct: lives for as long as the struct
The compiler does not need a 'a annotation because a token is a value, and its lifetime is managed uniformly by the ownership system (Move/RAII). This reduces the borrow problem to an ownership problem.
2.5 Token Conflict Detection
Token conflict detection is a Hoare logical proposition, not an independent flow-sensitive analysis.
{冲突的 ReadToken 全部死亡} write(data) {WriteToken 安全获取}It shares RFC-027's proof pipeline with type checking and user-predicate verification. The compiler automatically generates borrow propositions (borrow_conflict, use_after_move, use_after_drop, mut_violation) and sends them into the pipeline for validation. The pipeline returns Proved / Disproved / Unproven.
# ❌ An &mut token is linear and cannot be copied
bad_dup: (p: &mut Point) -> Void = {
p2: &mut Point = p # Move; p can no longer be read
p.x = 10.0 # ❌ Compile error: the WriteToken has been moved
}
# ✅ An &T token is a Dup type and can be copied freely
good_dup: (p: &Point) -> Void = {
p2: &Point = p # OK; &T is a Dup type
print(p.x) # OK
print(p2.x) # OK; two read-only tokens coexist
}Borrow checking has not disappeared—it has been reduced in dimensionality. The existing BorrowChecker becomes a BorrowPredicateEmitter (proposition generator), and the generated borrow propositions share the same proof pipeline as all other type propositions. This is exactly parallel to the type checker: the type checker generates type-equality propositions, the borrow-proposition generator generates borrow propositions, and the same pipeline validates them. See RFC-009a for the detailed design.
2.7 Compiler Internals: Branding Mechanism
Users never encounter brands. Internally, the compiler assigns each token a compile-time unique identifier:
用户看到的编译器内部表示
────────────────────────────────────────
&Point → ReadToken(Point, #N) // #N is a compile-time unique integer
&mut Point → WriteToken(Point, #M) // #M is a compile-time unique integerBrands serve the following purposes:
- Forgery prevention: Tokens can only be obtained from their owning capsule and cannot be fabricated from nothing
- Association tracking: When deriving
&Floatfrom&Pointthrough field access, the&Floatcarries a derived brand (#N.field_x), allowing the compiler to trace it back to the parent token - Conflict detection: A
WriteTokenand a derivedReadTokenfrom the same source cannot be active simultaneously
Brands disappear completely after monomorphization and inlining and do not exist in the generated machine code. Zero runtime overhead.
2.8 Automatic Borrow Selection Rules
At the call site, the compiler selects automatically according to the following priorities:
1. 如果实参后续还有使用 → 优先创建令牌(&T 或 &mut T,根据方法签名)
2. 如果实参后续不再使用 → Move
3. 优先匹配顺序:&T < &mut T < Move# Example: automatic selection
p = Point(1.0, 2.0)
p.print() # print declares &self → the compiler creates an &Point token
p.shift(1.0, 1.0) # shift declares &mut self → the compiler creates an &mut Point token
p2 = p # Move; p is not used again2.9 Comparison with RFC-009 v8's Stripped-Down Borrowing
| Feature | Stripped-Down Borrowing (v8) | Borrow Tokens (v9) |
|---|---|---|
| Returning references | ❌ Hardcoded prohibition | ✅ Tokens propagate with return values |
| Storing in structs | ❌ Hardcoded prohibition | ✅ Tokens as struct fields |
| Explicit Lambda arguments | ❌ Hardcoded prohibition | ✅ Lambdas use explicit arguments |
| Special rules | 3 (parameter-only/cannot return/cannot store) | 0—permissions are inferred naturally from type attributes |
| Borrow checking | Dedicated cross-borrow checking | Type checker flow-sensitive liveness analysis |
| Lifetime annotations | Not required | Not required |
| Runtime overhead | Zero | Zero (zero-sized types disappear after compilation) |
| Error messages | "Borrows cannot escape" | "WriteToken(#3) has been moved" (ordinary type error) |
| User mental model | Understand the special status of borrowing | &T is copyable; &mut T is not copyable |
3. The ref Keyword (Compiler-Automatic Optimization)
ref is the only way to share across scopes. Users do not need to care whether the underlying implementation is Rc or Arc.
3.1 Basic Usage
p: Point = Point(1.0, 2.0)
shared = ref p # Shared; the compiler automatically selects the implementation
# Cross-task sharing
@block
main: () -> Void = {
data = ref heavy_data
spawn { use(data) } # Compiler: cross-task → Arc
spawn { use(data) } # Compiler: cross-task → Arc
}
# Single-task sharing
@block
main: () -> Void = {
data = ref heavy_data
use(data) # Compiler: no cross-task → Rc
}User mental model: ref = shared ownership. That's all you need to know.
3.2 Compiler Escape Analysis: Rc vs. Arc
ref 的数据流分析:
不逃逸到其他任务 → Rc(非原子引用计数,开销低)
逃逸到其他任务 → Arc(原子引用计数,线程安全)3.3 Cycle Detection Strategy
任务内环 → 静默允许。
├── 每个任务有明确的生命周期边界——任务结束时所有资源(含 ref 环)统一释放。
├── 长期运行的服务应按请求/连接创建子任务——子任务结束自动回收,不会累积泄漏。
├── ref 永远保活,语义不掺水。
└── 用户有权在任务内构建双向强引用(例如图计算中间态)。
跨任务环 → lint(默认 warn,可配置)。
├── 程序行为正确,不会真泄漏(父任务结束时子任务资源全释放)。
├── 但跨任务强引用意味着所有权边界模糊,值得停下来重新思考。
├── 默认 warn 级别,编译通过但有提示。
└── 团队可在项目配置中设为 deny,纳入 CI 质量门。Lint levels (similar to Rust clippy):
| Level | Behavior | Scenario |
|---|---|---|
allow | No checks | Personal projects |
warn (default) | Compilation succeeds with warnings | Development phase |
deny | Compilation fails | Team CI quality gate |
forbid | Compilation fails and cannot be overridden | Organization-wide mandatory rules |
# In-task cycle: silently allowed, with bidirectional strong references
build_graph: () -> Void = {
a = Node("a")
b = Node("b")
a.next = ref b
b.prev = ref a # Cycle. Resources are released together when the task ends.
}
# Cross-task cycle: lint (warn by default)
@block
parent_task: () -> Void = {
shared_a = ref a
shared_b = ref b
spawn {
shared_a.child = ref shared_b # ⚠️ warn: cross-task reference cycle
}
}Project configuration example:
# yaoxiang.toml
[lints]
cross-task-cycle = "deny" # Reject cross-task cycles directly in CI| Cycle Type | Behavior | Reason |
|---|---|---|
| In-task ref cycle | No checks | A user privilege; resources are released together at task end |
| Cross-task ref cycle | Lint (warn by default) | Encourages reconsideration; deny can be configured |
3.4 Weak: Provided by the Standard Library
use std.weak
# Advanced users explicitly choose
a.next = ref b
b.prev = std.weak.new(a.next) # The user explicitly controls which direction is weakWeak is not built into the language; it is a standard-library type. For everyday use, ref is sufficient. Advanced users who need fine-grained control over memory can manually import Weak.
Revised on 2026-08-03: Implemented as an independent
std.weakmodule (std.rcdoes not exist—refis a language keyword rather than a module; the module path is uniformlystd.weak, and the construction/upgrade entry points arestd.weak.new/std.weak.upgrade). Thestd.rc.Weakenvisioned in the initial draft was not implemented; this revision takes precedence.
3.5 Borrow Tokens vs. ref
&T / &mut T | ref | |
|---|---|---|
| Purpose | Take a look / modify in place | Shared ownership |
| Scope | Follows the scope of the token value | Crosses scopes |
| Cost | Zero overhead (zero-sized types) | Rc or Arc (compiler-selected) |
| Escaping | Possible (tokens propagate through return values, structs, and closures) | Intended for escaping |
| Cross-task | Not possible (tokens are compile-time permission proofs and cannot cross tasks) | Possible (the compiler automatically selects Arc) |
| Cycles | Not applicable | Silently allowed in-task; cross-task lint |
4. clone() — Explicit Copy
p: Point = Point(1.0, 2.0)
p2 = p.clone() # Deep copy
# p and p2 are independent and do not affect each otherWhen to use it: When the original value must be retained in a situation where neither Move nor sharing is appropriate.
5. unsafe + Raw Pointers (Systems-Level Programming)
p: Point = Point(1.0, 2.0)
unsafe {
ptr: *Point = &p # Raw pointer
(*ptr).x = 0.0 # Dereference (the user guarantees safety)
ptr2 = ptr + 1 # Pointer arithmetic
}Restrictions:
- May only be used inside an
unsafeblock - The user guarantees that pointers do not dangle and are not used after being freed
- Intended for FFI, memory operations, and other systems-level programming
6. Ownership Gradient Overview
借用令牌(零开销) Move(零开销) 共享(按需付费) 复制
│ │ │ │
&T 可复制令牌默认所有权转移 ref Rc/Arc clone()
&mut T 线性令牌链式消费回流编译器自动选显式深拷贝
│ │ │ │
令牌值作用域作用域内跨作用域任何时候
可返回/存结构体 T -> T 回流 ref 跨任务 → Arc 独立副本
零大小编译后消失 T -> Void 消费 ref 不跨任务 → Rc
零大小编译后消失任务内环静默
跨任务环 lint
标准库 Weak 逃生Comprehensive Example
Point: Type = {
x: Float,
y: Float,
# &T: read-only token
print: (self: &Point) -> Void = {
print(self.x)
print(self.y)
}
# &mut T: mutable token
shift: (self: &mut Point, dx: Float, dy: Float) -> Void = {
self.x = self.x + dx
self.y = self.y + dy
}
# Move → Move: consume and return
scale: (self: Point, f: Float) -> Point = {
self.x = self.x * f
self.y = self.y * f
self # Take it, modify it, and give it back
}
# Return a reference: the token propagates with the return value
get_x: (self: &Point) -> (&Float, &Point) = {
return (&self.x, self)
}
}
# Explicit Lambda arguments
double: (x: Int) -> Int = (x) => x * 2
# Comprehensive usage
p = Point(1.0, 2.0)
p.print() # &Point token
p.shift(1.0, 1.0) # &mut Point token
p = p.scale(2.0) # Move → return
shared = ref p # ref sharing
spawn { use(shared) }
# Independent clone
backup = p.clone()
# In-task cycle: silently allowed
a = Node("a")
b = Node("b")
a.next = ref b
b.prev = ref a # Cycle; resources are released together when the task ends
# System-level unsafe
unsafe {
ptr: *Point = &p
(*ptr).x = 0.0
}Type System Constraints
Dup Type Attribute
Dup (Duplicable) is a compiler-managed type attribute meaning shallow copy: assignment or argument passing copies the handle/token while the underlying data is shared. This forms a three-level gradient with Move (ownership transfer) and Clone (explicit deep copy that creates an independent copy).
Dup and Clone are orthogonal concepts—Dup copies a handle and shares the data, whereas Clone creates an independent copy. A type may support both Dup and Clone, or only one of them.
| Type | Dup | Clone | Description |
|---|---|---|---|
&T | ✅ (copies the token; multiple views point to the same data) | ✅ | Read-only token |
ref T | ✅ (reference count +1; shares heap data) | ✅ | Shared ownership (the compiler automatically selects Rc/Arc) |
| String, Bytes | ✅ (internal reference count; copying the handle shares the underlying buffer) | ✅ | String/bytes |
&mut T | ❌ (linear, exclusive) | ❌ | Mutable token |
*T | ❌ | ❌ | Raw pointer |
| struct | Derived (see "Derivation Rules," #398) | ✅ | Struct |
| tuple | Derived (element by element, using the same rules as struct, #398) | ✅ | Tuple |
Primitive value types (Int, Float, Bool, Char) use the compiler's built-in value-copy behavior for assignment—the two values are completely independent rather than shallow copies. They do not belong to the Dup type attribute; they are handled natively by the compiler.
Derivation Rules (Finalized in #398)
The rule "automatically derive Dup when all fields are Dup" cannot be applied literally—primitive fields such as Int are not themselves Dup, so { x: Int, y: Int } would be misclassified as Move. An executable formulation is:
- Copyable field set = ValueCopy (Int / Float / Bool / Char / Range) ∪ Dup (
&T,ref T, String / Bytes, function values (#352), and composite types that are already Dup); - struct: If all fields belong to the copyable field set → derive Dup. If any field is Linear (
&mut T) or Move (a nested Move struct, containers such as Vec / Dict, or a resource) → the entire value remains Move (no "partially copyable" intermediate state is introduced—its copying semantics require a transfer); - tuple: Uses the same rules as struct, evaluated element by element; the empty tuple (unit) is
Void; - Derivation is recursive: When a field has a named type, such as
target: Point, its definition is expanded before evaluation.A = { b: B }follows B's derivation result; recursive aliases conservatively remain Move when the depth limit is reached; - Out of scope for this RFC (remain Move and will be addressed separately): containers (Vec / Dict / Set / Option / Result / Array) and enum.
Performance Analysis
| Operation | Cost | Description |
|---|---|---|
| Move | Zero | Pointer movement |
&T / &mut T | Zero | Zero-sized types disappear after compilation; zero runtime overhead |
ref (no cross-task) | Low | Compiled to Rc, with non-atomic operations |
ref (cross-task) | Medium | Compiled to Arc, with atomic operations |
clone() | Type-dependent | Fast for small objects, slow for large objects |
unsafe + *T | Zero | Direct memory operations |
Comparison
| Language | Sharing Mechanism | Memory Management | Cycle Handling | Complexity |
|---|---|---|---|---|
| Rust | Arc / Mutex + borrow checks | Compile-time checks | Manual Weak | High |
| Go | chan / pointer | GC | GC | Low |
| C++ | shared_ptr | RAII | weak_ptr | Medium |
| YaoXiang | ref + borrow tokens | RAII | Task-boundary release / cross-task lint / standard-library Weak | Low |
Trade-offs
Advantages
- Unified:
&T/&mut Tare ordinary types, not special language features. They are fully consistent with RFC-010'sname: type = value - Simple: No lifetimes, and borrow checking is reduced to type-system propositions.
&Tis copyable and&mut Tis not—two type attributes - Powerful: References can be returned and stored in structs, and closures can capture—all with expressiveness comparable to Rust
- Compiler intelligence: ref automatically selects Rc/Arc, and call sites automatically select borrowing
- Deterministic: ref means keep-alive and never silently becomes a weak reference
- High performance: Move is zero-copy, and tokens have zero overhead (zero-sized types disappear after compilation)
- Flexible:
unsafe + *Tsupports systems-level programming
Disadvantages
- Generic brand-parameter contagion: Tokens carry brand identifiers, so signatures of functions that return references exhibit additional generic parameters
- ref runtime overhead: Atomic operations have a cost (but this is an unavoidable consequence of sharing)
- unsafe risks: Users must guarantee correctness
- Cross-task cycles are lints rather than compile errors: Unlike Rust, they produce warnings by default and must be configured as deny by a team to serve as a quality gate
Alternatives
| Alternative | Why It Was Not Chosen |
|---|---|
| GC | Runtime overhead and unpredictable pauses |
| Rust borrow checker | Requires lifetimes 'a and has a steep learning curve |
| Pure Move | Cannot handle concurrent sharing |
| No raw pointers | Cannot support systems-level programming |
| Expose Rc/Arc to users | Pushes implementation details onto users and increases cognitive load |
| Stripped-down borrowing (v8) | Its escape-prohibition strategy sacrifices essential expressive capabilities such as closure capture and returning references |
Design Decision Record
| Decision | Resolution | Reason | Date |
|---|---|---|---|
| Default value | Move (zero-copy) | High performance with zero overhead | 2025-01-15 |
| Sharing mechanism | ref keyword with compiler-selected optimization | Simple for users; handled by the compiler | 2025-01-15 |
| Borrowing | &T/&mut T as zero-sized token types | Permissions are inferred naturally from type attributes (Dup/Linear), unifying them with the type system | 2025-01-15 |
| Borrow tokens | Replace stripped-down borrowing; &T is Dup and &mut T is Linear | Eliminates special rules such as "escape prohibition" and supports closure capture, returning references, and storing tokens in structs | 2026-05-29 |
| Copying | clone() | Explicit semantics | 2025-01-15 |
| Systems-level access | *T + unsafe | Supports systems programming | 2025-01-15 |
| Lifetimes | Not implemented | Tokens are values whose lifetimes are managed uniformly by Move/RAII, reducing borrowing to an ownership problem | 2025-01-15 |
| Rc/Arc | Automatically selected by the compiler and invisible to users | Reduces cognitive load | 2025-01-15 |
| Reference cycles | No in-task checks; cross-task lint (warn by default) | Structured concurrency provides natural guarantees, and lint can be configured as deny | 2025-01-16 |
| Weak | Provided by the standard library | Explicitly selected by advanced users | 2025-01-16 |
| Consumption analysis | Removed | A mini borrow checker is unnecessary | 2026-05-11 |
| Ownership flow-back | Removed | A (T) -> T signature is itself documentation | 2026-05-11 |
| Empty-state reuse | Removed as a feature | Reassignment after Move is natural behavior | 2026-05-11 |
| Inverse functions/partial consumption/field-level three-layer mutability | Removed | Overdesign | 2026-05-11 |
| Lambdas do not implicitly capture | Lambdas use only explicit arguments and do not implicitly capture outer variables; context is fixed at the creation point through currying (SPEC §12.3) | The scope where a closure was defined may already be dead; a fixed value is safe at the creation point because the call-site scope remains alive | 2026-06-16 |
Version History
| Version | Major Changes | Date |
|---|---|---|
| v1 | Initial draft: based on Rust's ownership model | 2025-01-08 |
| v8 | Removed overdesign (inverse functions/partial consumption/field-level three-layer mutability/consumption analysis/ownership flow-back/empty-state reuse) and added stripped-down borrowing &T/&mut T | 2026-05-11 |
| v9 | The borrow-token system replaced stripped-down borrowing and unified the type system; token conflict detection was corrected to Hoare propositions, as described in RFC-009a | 2026-06-13 |
Open Issues
| Issue | Description | Status |
|---|---|---|
| Drop syntax | Whether an explicit drop() function is needed | Under discussion |
| Escape-analysis algorithm | Implementation of ref cross-task detection | Under discussion |
| Token conflict detection | Hoare logical proposition; see below | ✅ Resolved (see RFC-009a for details) |
Token Conflict Detection: Hoare Logical Propositions
The complete proposal for token conflict detection is described in RFC-009a: Token Lifetime Analysis—Based on the Hoare Proof Pipeline. Its core points are:
Token liveness is a Hoare logical proposition.{冲突的 ReadToken 全部死亡} write(data) {WriteToken 安全获取}—it shares RFC-027's proof pipeline with type checking and user-predicate verification. The compiler automatically generates borrow propositions (borrow_conflict, use_after_move, use_after_drop, mut_violation), and the pipeline returns Proved / Disproved / Unproven.
Borrow checking has not disappeared—it has been reduced in dimensionality. BorrowChecker becomes a BorrowPredicateEmitter that generates propositions rather than performing checks. This is exactly parallel to the concept of a "type checker": the type checker generates type-equality propositions, the borrow-proposition generator generates borrow propositions, and the same pipeline validates them.
A brand ID (#42) is 'a. The information is exactly the same; only the encoding differs. 'a is visible in type signatures, while #42 is internal to the compiler. No new analysis has been invented—lifetimes have been moved from the type layer to the proof layer.
Algorithm summary (see RFC-009a for details):
- Brand-tree prefix matching → identify conflicting tokens (O(depth), depth ≤ 3)
- Reverse BFS → start from the consumer, and break cuts back edges; structural analysis covers more than 95% of scenarios (fast path)
- SMT logical cut → invoked only for while + path conditions (slow path, extremely rare)
References
Official YaoXiang Documentation
- Language Specification
- Design Manifesto
- RFC-009a: Token Lifetime Analysis—Based on the Hoare Proof Pipeline
- RFC-010 Unified Type Syntax
- tutorial/ Tutorial
External References
Lifecycle and Disposition
| Status | Location | Description |
|---|---|---|
| Draft | docs/design/rfc/ | Author's draft, awaiting submission for review |
| Under Review | docs/design/rfc/ | Open for community discussion and feedback |
| Accepted | docs/design/accepted/ | Becomes an official design document |
| Rejected | docs/design/rfc/ | Retained in the RFC directory |
