Skip to content

RFC-009a: Token Lifetime Analysis—Based on the Hoare Proof Pipeline ​

Parent RFC: RFC-009: Ownership Model Design

Dependency: RFC-027: Compile-Time Predicates and Unified Static Verification

Prerequisite: RFC-027 has been accepted. All mechanisms in this RFC—the proof pipeline, SMT fallback, and path-condition collection—depend on RFC-027's implementation.

This RFC corrects and supersedes RFC-009 §"Token Conflict Detection: Flow-Sensitive Liveness Analysis" (lines 663-684).

Abstract ​

RFC-009 line 684 claims that token conflict detection "does not require ... NLL." The conclusion is correct, but the reasoning is wrong.

It is not "because tokens are values, so linear tracking is sufficient." It is because token liveness is a Hoare logic proposition, not a specialized flow-sensitive analysis.

{conflicting_tokens all dead} op {WriteToken safely acquired} — the same {P} op {Q} form shared with type checking and predicate verification in RFC-027's proof pipeline. There is no new analysis framework. One pipeline, many kinds of proposition.


Motivation ​

RFC-009's confusion ​

RFC-009 conflates two questions:

  1. Linear tracking (unavailable after a move)—{v has not been moved} use(v) {type matches}. The type checker already handles this.
  2. Token lifetime interactions (child token alive → parent token suspended → child token dies → parent token revives)—{conflicting_tokens all dead} write(data) {safe}. This requires liveness analysis, not linear tracking.

The actual state of the current code ​

ComponentStatus
BorrowCheckerLinearly scans the IR and passively responds to explicit Borrow/Release instructions
ControlFlowAnalyzer::analyze_instructionEmpty implementation (control_flow.rs:145-153)
liveness_analysisExists, but is used only for Drop insertion and is not connected to token conflicts
Release insertionHardcoded after Call instructions—purely lexical scope (ir_gen.rs:2734-2736)

User-visible consequence:

yaoxiang
data = vec![1, 2, 3]
view = &data              # Creates a ReadToken
x = view.total_count      # Last use of view
data.push(4)              # ❌ Release(view) has not run yet; the ReadToken is still "alive"

Why a rewrite is needed ​

The previous version (009a v1) used a "replace NLL with a DAG" narrative and introduced unnecessary new concepts (conservative branch rules, special handling for loops). It failed to articulate the core contradiction: borrow checking is not an independent system—it is one kind of Hoare proposition.


Core Design ​

Everything Is Hoare ​

类型检查:  { x: Int }        x + 1        { result: Int }
借用检查:  { view 已死 }     data.push(4)  { WriteToken 获取成功 }
谓词验证:  { y > 0 }         divide(x, y)  { result: Int }
回边切断:  { i == n }        下一轮循环     { cond == false }

The same form {P} op {Q}. For every operation, the compiler generates a precondition proposition P and sends it through the proof pipeline for verification.

Borrow checking and user predicates share the same pipeline. The only differences are who generates the proposition and what happens when it cannot be proved.

Two Kinds of Predicates, One Pipeline ​

User predicatesSystem predicates (borrowing)
Proposition generationProgrammer (type annotations)Compiler (brand tree + ownership rules)
Proof providerCompiler + programmerFully automated by the compiler
If unprovableWrite a proof function or refactorRefactor the code (the gate remains, but is rarely needed)
VisibilityVisible in the signatureImplicit; does not pollute the type signature
Learning costLearn only if neededZero

The compiler automatically discharges proofs of system predicates; it does not ask programmers to write proof functions. When it cannot prove a proposition, the user refactors the code.

Three failure modes, one verification engine. If a type proposition cannot be proved → compile error (cannot be bypassed). If a borrow proposition cannot be proved → compile error and code refactoring (cannot be bypassed). If a user predicate cannot be proved → compile error, but a proof function may be written (can be bypassed). The failure policies differ, but the verification engine is the same—an SMT solver plus compiler-internal inference rules. The only difference is "who is responsible for supplying the proof when a proposition cannot be proved." The compiler refuses to write borrow proofs on the programmer's behalf—the borrow-proposition proof strategy consists of structural analysis + SMT and requires no programmer intervention—but it accepts programmer-written proof functions for user predicates. This is not an inconsistency in the pipeline; it is a difference in responsibility boundaries between categories of propositions.

This differs from Rust's 'a: 'a is a required course, while proof functions are an elective—most users never encounter the elective's gate.

Borrow Propositions: Automatically Generated by the Compiler ​

When the user writes data.push(4), the compiler automatically generates the proposition:

WriteToken(data, node) 可获取
  = forall t in conflicting_tokens(data): t 在 node 处已死
  = forall t in brand_tree.children(data): forward_reachable(node) ∩ consumers(t) == ∅

Three rules, with no special cases:

  1. The brand tree (RFC-009 §2.7) answers "who conflicts with whom": prefix matching, O(depth), depth ≤ 3
  2. The consumer list (automatically collected while building the DAG) answers "who last consumes each token"
  3. Forward reachability answers "whether a consumer can still be reached": structural cut + logical cut

Forward Reachability: Walk Backward from Consumers ​

For every consumer C of token T:

从 C 出发,反向 BFS DAG。
边被切断,如果:
  1. 它是 break(结构切断)
  2. 路径条件 ⇒ !loop_cond 被 SMT 证明为真(逻辑切断,RFC-027 管道)

沿所有未切断的边反向传播(包括回边,回边将活性传播到前一轮迭代)。
标记所有能到达的节点 → unsafe。

Query: the write operation is at node W → W ∉ unsafe → safe.

There is no need to invent "conservative branch rules." There is no need for "conservative liveness within loops." One reverse BFS + two cutting rules.

Proof Strategy: Fast Path First, SMT as Fallback ​

每个需要令牌的写操作
  │
  ├→ 快速通道:DAG 结构分析(覆盖 95%+ 场景)
  │     │
  │     ├→ 品牌树前缀匹配 → 找出冲突令牌(O(depth))
  │     ├→ 反向 BFS,break 切断回边
  │     └→ 无回边可穿越 → 直接判定 Proved / Disproved
  │
  └→ 慢速通道:SMT 逻辑切断(仅当快速通道遇到可穿越回边时)
        │
        ├→ 回边起点有路径条件 → SMT 判 path_cond ⇒ !loop_cond
        │     ├→ Proved → 逻辑切断 → 降级回快速通道继续
        │     └→ Disproved / Unproven → 回边穿越 → 标记 unsafe
        │
        └→ 回边起点无路径条件 → 回边直接穿越

Fast-path coverage: linear code, if/else, loop + break, and while loops without path conditions. Slow-path coverage: while-loop bodies where a path condition indicates that the loop will exit. Not covered: runtime conditions that cannot be proved statically → traverse the back edge → unsafe → compile error (the user refactors).

SMT is not the primary mechanism—it is a safety net. Unlike RFC-027's user predicates, user predicates rely primarily on SMT; borrowing system predicates rely primarily on structural analysis, with SMT covering only the edges that structural analysis cannot reach.

SMT is a precision layer, not a soundness dependency. The sound verdict for borrowing system predicates is handled entirely by the fast path (interval + reverse BFS + break cut); SMT logical cuts only determine whether "a valid program at a loop boundary may be admitted." When SMT is unavailable, times out, or is unimplemented (RFC-027 impl: in_progress), the fallback is to traverse the back edge and conservatively reject the program; everything that should be rejected is still rejected. Conservatism without SMT is equivalent to rejecting every borrow + write inside a loop, on par with Rust NLL (Rust's production-grade borrow checking likewise uses no SMT). SMT is a pure precision gain and does not block delivery of the sound core.


Use-Case Analysis ​

Linear Code ​

yaoxiang
data = vec![1, 2, 3]        # Node 1
view = &data                # Node 2: consumes data, produces ReadToken(#1)
x = view.total_count        # Node 3: consumes view (the last consumer of #1)
data.push(4)                # Node 4: requires WriteToken(data)

Reverse BFS starts from view.total_count (node 3) → node 3 is the last consumer of #1 → node 4 > node 3 → node 4 is not unsafe → ✅

if/else: No Special Rules ​

yaoxiang
view = &data
if cond {
    use(view)               # The then branch consumes view
} else {
    do_something_else()     # Does not touch view
}
data.push(4)                # The last consumer of view is inside the if → no consumer after the if → ✅

An if/else is a composite node in the DAG. Internal consumption is attributed to this node. It does not merge branch states or conservatively combine them. Whether a later consumer exists comes down to an integer comparison.

Clarification: "does not merge branch states" refers only to borrowing liveness (backward BFS over brand consumers). Move state (variable ownership) is a separate analysis: per-CFG-node forward dataflow (NLL/Polonius style), with a conservative meet at branch joins (Moved in either branch → Moved at the join). A branch made unreachable by a literal (if false) does not participate. The two analyses are layered: borrowing liveness asks "is there a later consumer?", while move analysis asks "might the variable already have been transferred?"

if/else with a Returning Value That Escapes ​

yaoxiang
view = &data
result = if cond {
    view                     # view escapes into result
} else {
    something_else
}
use(result)                  # Indirectly consumes view
data.push(4)                 # view still has a consumer (use(result))
                             # → push is in unsafe → ❌ correct error

view escapes through the return value → use(result) is a consumer of view → walking backward from push reaches use(result) → unsafe.

Loops: break Cuts the Back Edge ​

yaoxiang
view = &data
loop {
    use(view)                # consumer
    if is_last {
        data.push(4)         # write operation
        break                # ← structural cut
    }
}

Reverse BFS starts from use(view) → back edge → moves forward to data.push(4) → encounters break → cut → data.push(4) is not unsafe → ✅

Without a break:

yaoxiang
view = &data
loop {
    use(view)
    data.push(4)             # No break cut → the back edge can be traversed → use(view) in the next iteration is reachable
                             # → push is in unsafe → ❌ correct error
}

while: SMT Logical Cut ​

yaoxiang
view = &data
mut i: UpTo(n) = 0
while i < n {
    use(view)                # consumer
    i += 1
    if i == n {
        data.push(4)         # Path condition: i == n
    }
}

Reverse BFS starts from use(view) → back edge → reaches data.push(4) → checks the path condition i == n → SMT query: i == n ⇒ !(i < n)? → Proved → logical cut → data.push(4) is not unsafe → ✅

Note that the decision target is the write node's own path condition (i == n belongs to data.push(4) inside the if branch), not the path condition of the back-edge node.


Essence: A Brand ID Is 'a ​

Do not say "we do not need 'a." Say "#42 is '42."

RustYaoXiangEquivalence
'a#42Compile-time lifetime identifier
'a: 'b outlives constraint#42 is a prefix of #42.field_xString prefix comparison = partial order
NLL liveness propagation (CFG fixed point)Reverse BFS (DAG)Both are reachability computations
Polonius factsSMT logical cutBoth are path-condition reasoning
Constraint-system fixed-point solvingBrand-tree prefix matching + BFSDifferent encoding, same problem

We have not invented a new analysis. We have merely lowered 'a from the type-signature layer to the proof layer. A brand ID does exactly what 'a does—it identifies a borrow, tracks derivation relationships, and determines conflicts. There is only one difference: 'a appears in type signatures written by users; #42 exists inside the compiler.

There is nothing shameful about this. Curry-Howard says that types are propositions and programs are proofs. 'a is not part of the proposition—it is part of the proof strategy. Rust writes the proof strategy into the proposition's signature. We put it back where it belongs.

What Language Design Constraints Eliminate ​

Source of complexityAvoided?Reason
Variable shadowing✅The language prohibits it—one name always refers to the same thing
Borrowing across for iterations✅Every iteration has a new binding—iterations are naturally isolated
'a lifetime annotations✅Brand paths such as #42.field_x are inferred by the compiler
Named lifetimes + constraint propagation✅Brand-path prefix comparison replaces explicit constraint sets
Borrow-graph constraint solving (Polonius)✅Brand-tree prefix matching + DAG consumer queries
Borrow-liveness propagation within loop bodies❌As in Rust, this must be handled—using reverse BFS + logical cuts
Conservatism for conditional branches❌As in Rust—SMT covers what can be proved, and the remainder is conservatively rejected

Why a DAG Is Feasible ​

Three language-design constraints in YaoXiang make DAG analysis feasible:

  • No variable shadowing—one name always refers to the same thing, eliminating the need to track rebinding
  • A new binding for every for iteration—iterations are naturally isolated, with no borrowing across iterations
  • Structured concurrency—clear task boundaries eliminate the need for liveness propagation across tasks

These constraints eliminate the main sources of complexity in Rust's CFG fixed-point iteration. A DAG is not "more advanced" than a CFG—simpler language design permits simpler analysis.


Detailed Design ​

System Predicate Inventory ​

The compiler automatically generates the following propositions and sends them through the RFC-027 proof pipeline:

System predicateTriggerProposition form
borrow_conflictRequires WriteToken(v)forall t ∈ conflicting(v): dead_at(t, node)
use_after_moveUses variable v¬moved(v)
use_after_dropUses variable v¬dropped(v)
double_dropDrop(v)¬dropped(v)
mut_violationWrites to immutable variable vis_mut(v)

The existing BorrowChecker, MoveChecker, DropChecker, and MutChecker become proposition emitters—they do not disappear; they change identity. They generate propositions, and the pipeline verifies those propositions.

Brand Tree ​

RFC-009 §2.7's brand mechanism is formalized as a brand tree.

Token semantics—freezing takes priority over copying:

The essential difference between &T and &mut T is not "whether it can be copied," but "whether concurrent writing is allowed":

ReadToken(T): 授予只读权限,同时冻结源数据 T——任何 WriteToken(T) 在此期间
              不可获取。冻结是 ReadToken 的首要语义。Dup(可复制)是冻结的推论:
              因为数据已被冻结(无突变可能),多份只读视图天然安全。

WriteToken(T):授予独占读写权限。因为存在写,任何其他令牌(读或写)都不可共存。
              不实现 Dup(线性类型)是独占的推论。

Causal relationship:

ReadToken 存在 → 源数据冻结 → 多份只读安全 → Dup
                      ↓
              WriteToken 被拒绝(borrow_conflict 系统谓词强制)

Not:

ReadToken 有 Dup → 可以有多个 → 顺便检查冲突  ← 因果倒置
BrandTree:
  nodes: Map<BrandId, BrandNode>

BrandNode:
  id: BrandId               # "#42", "#42.field_x"
  kind: ReadToken | WriteToken
  source_var: Operand
  parent: Option<BrandId>   # Parent node of the derivation relationship
  children: Set<BrandId>    # Derived child tokens
  consumers: Set<NodeId>    # DAG nodes that consume this token
  ref_count: usize          # Number of safe copies while the ReadToken holds the freeze

Conflict determination—the enforcement mechanism for the freezing guarantee:

rust
fn conflicts(a: &BrandId, b: &BrandId) -> bool {
    // Conflict condition: same source + at least one side is a write + overlapping brand paths
    // This means:
    //   1. ReadToken vs ReadToken → no conflict (both are read-only, so there can be no mutation)
    //   2. WriteToken vs ReadToken → conflict (the write breaks the read's freezing guarantee)
    //   3. WriteToken vs WriteToken → conflict (two writes cannot coexist)
    a.source() == b.source()
        && (a.is_write() || b.is_write())
        && (a.is_prefix_of(b) || b.is_prefix_of(a))
}

O(depth) string-prefix comparison, depth ≤ 3. Constant-time.

Reverse-BFS Liveness Analysis ​

This algorithm introduces a "token creation time" dimension. Token liveness is an interval[created_at, last_use], not a reverse-reachable set; a write operation conflicts only within the token's live interval. This covers the valid "write first, borrow later" ordering (§2.4 semantics: a parameter token is released when the call ends), avoiding a false positive.

算法:check_borrow(token, node, dag, brand_tree)

输入:
  token: 需要检查的 WriteToken
  node:  写操作所在的 DAG 节点

输出:Proved | Disproved

算法:
  # Fast path: reverse BFS
  unsafe = empty_set
  queue = brand_tree.consumers(token)

  while queue not empty:
    cur = queue.pop()
    unsafe.add(cur)

    for each pred in dag.predecessors(cur):
      # Structural cut: do not traverse break
      if pred 是 break 边:
        continue

      # Back edge → check whether SMT fallback is needed
      if pred 是回边:
        path_cond = 写节点 node 的路径条件   # The decision target is the write node's own condition
        loop_cond = 循环条件
        # First check whether it can be cut structurally (the corresponding break has already cut the path → this path is not taken)
        # Then examine the path condition
        if path_cond 非空:
          result = smt_fallback(path_cond, loop_cond)   # ← Slow path
          if result == Proved:
            continue                    # Logical cut
        # No path condition, or SMT cannot prove it → traverse the back edge
        # fall through

      if pred ∉ unsafe:
        queue.push(pred)

  # Decision (write first, borrow later)
  # node < created_at(token) → the token did not exist when the write occurred → Safe
  if node ∈ unsafe and created_at(token) ≤ node:
    return Disproved
  else:
    return Proved


smt_fallback(path_cond, loop_cond):
  # Called only when there is a back edge + a path condition
  # Uses the RFC-027 proof pipeline and shares the same SMT solver and budget
  return smt.prove(path_cond ⇒ !loop_cond)
  # Proved → logical cut
  # Disproved / Unproven → do not cut; traverse the back edge (conservative rejection)
  # SMT unavailable/timed out/unimplemented = Disproved branch—
  # SMT affects only precision (whether a valid program can pass), not soundness (everything that must be rejected is rejected);
  # Without SMT, conservatism = rejecting every borrow + write within a loop, on par with Rust NLL.

BrandNode gains the following field:

BrandNode:
  ...
  created_at: NodeId         # Token creation node (left endpoint of the borrow interval)

O(N), where the number of SMT calls = the number of back edges × the proportion of back edges with path conditions. SMT calls are extremely rare in the actual implementation—they are triggered only inside while loops when path conditions contain refined type variables.

Path-Condition Collection ​

This is provided by the existing mechanism in RFC-027 §3.2-3.3:

  • if guard: if y > 0 → the true branch pushes y > 0
  • match pattern: if let Some(v) = opt → the branch pushes opt == Some(v)
  • Assignment: i += 1; the compiler maintains variable range information
  • while cond: the loop body pushes cond == true

Each DAG node carries a set of path conditions. When reverse BFS traverses a back edge, it takes the path condition at the back edge's origin and uses SMT to determine whether the next iteration's loop-entry condition is excluded.

Path-condition propagation rules:

  1. A path condition is attached to the write node itself: a write operation W within a branch carries that branch's condition (if i == n { W } → path_cond(W) = i == n). When reverse BFS traverses a back edge, SMT evaluates path_cond(W) ⇒ !loop_cond (a path that can reach W must exit the loop → the consumer in the next iteration is unreachable → cut), not the back-edge node's path condition.
  2. Conservative clearing at joins: an if/else join point does not carry path conditions from within either branch (the disjunction of the two branch conditions is generally undecidable, so it is cleared directly). A write operation after the join has an empty path_cond → traverse the back edge.
  3. Semantic path conditions: path_cond is a ConstExpr (the semantics defined in RFC-027 §3.2), not source text; smt_cut translates it into an SMT constraint and solves it.
  4. No path condition → traverse the back edge directly (unsafe); do not invoke SMT.

Interface with RFC-027 ​

Borrowing system predicates and user predicates share the same proof pipeline; the difference lies in their primary proof strategies:

Query typeProposition sourcePrimary strategyFallback
Type equalityType checkerStructural equivalence—
User predicateProgrammer type annotationSMTProgrammer proof function
Borrow conflictAutomatically generated by the compilerDAG structural analysis (fast path)SMT logical cut

The SMT solver's role in borrow checking is: not the primary mechanism, but a safety net. It is invoked only when a while-loop back edge requires a logical cut. The vast majority of borrow checks complete on the fast path—O(N) reverse BFS with zero SMT overhead.

Relationship to the Existing Code ​

Existing componentHandling
BorrowCheckerBecomes BorrowPredicateEmitter—generates Hoare propositions for borrows
MoveCheckerBecomes MovePredicateEmitter—generates ¬moved(v) propositions
DropCheckerLikewise—generates Drop-related propositions
MutCheckerLikewise—generates is_mut(v) propositions
ControlFlowAnalyzerNo longer needed—the pipeline handles everything uniformly
liveness_analysisRetained—Drop insertion still requires variable liveness information
Hardcoded Release in ir_gen.rsRemoved—Release positions are driven by DAG consumer analysis

NLL and Iteration Boundaries ​

Token liveness is an interval [created_at, last_use], not a reverse-reachable set. created_at is the token creation node; last_use is the maximum consuming node identified by consumer analysis. The necessary and sufficient condition for write operation W and token T to conflict is: conflicts(T, W) ∧ created_at(T) ≤ node(W) ∧ node(W) can forward-reach last_use(T) (determined by reverse BFS). The valid "write first, borrow later" ordering (§2.4: a parameter token is released when the call ends) is directly excluded by created_at(T) ≤ node(W), without any special rules. This model makes the claim in §Trade-Offs, Advantage 5, "the algorithm is not conservative," hold under every ordering.

The token's death point is its last use (NLL), not the end of its lexical scope.

This is a natural consequence of consumer analysis: a consumer's position defines the token's last use. use(v) is a consumer of v → v dies immediately after use(v). No additional {} or drop() is needed to end the token's lifetime early.

A loop iteration boundary is the death line for token copies. Three rules:

规则 1:循环内声明的变量在每次迭代结束时自动死亡。
        for 的每次迭代是新绑定(语言设计保证),loop 同理。

规则 2:品牌树 ref_count 在循环头只计入循环外创建的副本。
        循环内 Dup 产生的新副本,ref_count 在迭代边界清零。

规则 3:反向 BFS 穿越回边时,不携带当前迭代的活性信息。
        只携带循环头处的 ref_count(即:循环外的副本)。

Example:

yaoxiang
view = &data                          # Loop head: ref_count = 1, consumer = use(view)
loop {
    v2: &Point = view                 # Dup inside the loop → ref_count = 2
    use(v2)                           # Consumer: last use of v2 → v2 dies → ref_count = 1
    data.push(4)                      # ✅ Safe! v2 is dead; only view remains (ref_count = 1, no write conflict)
    # Iteration boundary: Rule 3—do not carry v2 into the next iteration. At the start of the next iteration, v2 is recreated by a new binding.
}

This design does not require an additional "conservative liveness within loops" rule. Reverse BFS starts from the consumer; because the consumer is inside the loop body, liveness is confined to the current iteration → the back edge is not traversed. This is fully consistent with the loop example in RFC-009a §Use-Case Analysis.

? Error Propagation and Scope-Driven Release ​

? is an early return—an additional exit path beyond the normal scope exit. Tokens must be released along this path; releasing them in the wrong order results in UB.

Release instructions are generated by scope analysis, not hardcoded after Call.

The compiler maintains a list of exit points for every scope:

  • } (normal end of scope)
  • ? (error propagation and early return)
  • Explicit return

At every exit point, Release instructions are inserted in reverse declaration order (LIFO) for all live tokens in that scope. Parent-child relationships in the brand tree automatically handle cascading release of derived tokens:

yaoxiang
Point.get_x: (self: &Point) -> (&Float, &Point) = {
    return (&self.x, self)    # Returns the child token &Float + the parent token &Point
}

fn use_case(p: Point) -> Result<(), Error> = {
    (x_ref, p_ref) = p.get_x()?   # If ? propagates:
    # The brand tree knows that x_ref is derived from p_ref (#42.field_x is a prefix of #42)
    # Release order: x_ref (child) → p_ref (parent) → automatically satisfies LIFO
    p.modify()                     # WriteToken—all ReadTokens have been released
    Ok(())
}

Implementation location: retained in ir_gen.rs, but converted to scope-driven operation—no new compiler pass is introduced.

| Conflict check | O(1) | Every time a token is needed | | DAG consumer query | O(1) | Every time a token is needed | | Reverse BFS (fast path) | O(N) | Every time a token is needed, N = number of nodes in the block | | SMT logical cut (fallback) | ~1ms | Extremely rare—only while + a path condition |

The complexities in the table above are design estimates, not measured values; "~1ms" and "extremely rare" should be treated as order-of-magnitude expectations rather than measurements, and should be calibrated against observability data after implementation.

The conditions for triggering the SMT fallback are extremely restrictive: all four of the following must hold: (1) a while loop, (2) a write operation inside the loop body, (3) a path condition after the write that can determine loop termination, and (4) the compiler must rely on that condition to cut the back edge. Its prevalence in the actual implementation will be far below 1%. All other borrow checks complete on the fast path.

The relationship to RFC-027's user predicates is as follows: user predicates rely primarily on SMT, whereas borrowing system predicates rely primarily on structural analysis. Both share the same SMT solver and budget cap (RFC-027 §8), but borrowing system predicates consume virtually none of the SMT budget.

Linear code → no back edge → Tier 1 completes in O(N) time. A loop + path condition → an SMT invocation using linear arithmetic in milliseconds (RFC-027 budget: 100ms). One BFS result can be cached and reused for multiple queries involving the same token.

Error-Message Design ​

Core principle: error messages contain only symbols the user wrote.

Rust's borrow-related errors fall into two categories:

Variable-level errors: E0597 (does not live long enough), E0502 (mutable and immutable borrow at the same time), E0499 (multiple mutable borrows). Rust is already the benchmark—variable name + line number, with no 'a. YaoXiang matches Rust in precision. All the information is in the brand tree: token creation point, consumer location, and request point.

Signature-level errors: E0623 (lifetime mismatch), E0106 (missing lifetime specifier), E0477 (does not satisfy the required lifetime). These center on 'a. YaoXiang has no such errors—there is no 'a in its signatures. This is not "they cannot be reported"; it is that things the user never wrote need not be reported.

Example of a conflict within a function:

错误:`data` 被冻结,不能获取可变权限
 --> src/main.yx:5:9
2 |     view = &data
  |            ----- `data` 被冻结(只读令牌创建在此处)
4 |         use(view)
  |             ---- `view` 在此处仍在使用,冻结未解除
5 |         data.push(4)
  |         ^^^^ 此处需要可变权限

(On par with Rust E0499 in precision—variable name + line number, with no brand ID.)

Example of an escape across functions:

错误:`num`(第 4 行)持有的数据来源之一是 `default_str`(第 3 行),
但 `default_str` 在第 6 行失效,`num` 在第 5 行仍在被使用。

考虑:将 `default_str` 的声明提前到调用方,或使用 `ref default_str` 共享持有。

(On par with Rust E0597 in precision. The brand summary knows that num has two source paths—information already available in the compiler and usable in the error wording.)


Corrections to the Main Body of RFC-009 ​

RFC-009 §"Token Conflict Detection: Flow-Sensitive Liveness Analysis" has been updated:

  1. Remove "what is not needed: ... NLL"—not because the conclusion was wrong, but because the rationale was wrong ("tokens are values, so linear tracking is sufficient")
  2. Retain the Tier 1/Tier 2 transition solution; point the complete solution to this RFC
  3. Clarify that the brand ID (#42) is 'a—exactly the same information, encoded differently. This is not a new analysis—it moves the lifetime from the type layer to the proof layer

Trade-Offs ​

Advantages ​

  1. No lifetimes in type signatures: #42 is '42—the same information, encoded in the brand tree and not exposed in type signatures. This claim is unfalsifiable: count how many 'a parameters Rust's three generic types with reference parameters require, and how many YaoXiang requires. The answer is 3 vs 0.

  2. Conceptual unification: borrow checking and user predicates share one proof pipeline—{P} op {Q}, with the pipeline verifying P. Consistent with Curry-Howard.

  3. No new analysis framework: no new analysis framework is introduced. Users are unaware that a "borrow checker" exists—just as they are unaware of the type checker's implementation details.

  4. Error messages contain only symbols the user wrote: this eliminates an entire category of errors (E0623, E0106, E0477—all centered on 'a). Variable-level errors are on par with Rust in precision.

  5. The algorithm is not conservative: reverse BFS + break cuts + SMT logical cuts. No need for "conservative liveness within loops." No need for "conservative branch merging."

Disadvantages ​

  1. Not a new invention: a brand ID does exactly what 'a does—the constraint-solving complexity inside the compiler has not disappeared; only its encoding has changed from "variable name + constraint set" to "brand path + prefix matching." The only difference for end users is that the signature does not contain 'a.

  2. An entirely new implementation: the brand tree exists in the code only as a concept and must be implemented from scratch. BorrowChecker and ControlFlowAnalyzer are replaced.

  3. SMT dependency: logical cuts depend on Z3 (introduced by RFC-027, with no new dependency). Borrow checking rarely triggers it—only for while + a path condition.

  4. A small number of patterns require refactoring: users must refactor cross-branch borrows that the compiler cannot prove automatically. Unlike Rust's 'a fallback, where 'a acts as a crutch (adding the annotation makes it pass), YaoXiang's fallback—proof functions—is not part of the MVP.


Alternatives ​

AlternativeWhy it was not selected
Implement full Rust NLLYaoXiang's design constraints (no shadowing, new bindings for for) have already eliminated NLL's main sources of complexity, so a CFG fixed point is unnecessary
Keep the current approach (hardcoded Release)Insufficient—users must manually manage token scopes
Analyze only within spawn blocksInsufficient—token usage in non-spawn code is the majority
Replace borrow checking with a GCViolates the language-design principles—YaoXiang has no GC

Implementation Phases ​

PhaseContentsDependencies
Phase 1Brand-tree data structure implementation—
Phase 2System predicate emitters (Borrow/Move/Drop/Mut → propositions)Phase 1
Phase 3Reverse-BFS liveness analysis + pipeline integration (Tier 1)Phase 2
Phase 4Path-condition collection + SMT logical cuts (Tier 2)Phase 3 + RFC-027 Phase 2
Phase 5Release instructions driven by DAG consumersPhase 3
Phase 6Remove ControlFlowAnalyzer and refactor BorrowCheckerPhase 4

Open Questions ​

  • [x] Cross-iteration semantics for ref_count in the brand tree when loops are unrolled—follow NLL: a token dies after its last use. Copies bound within a loop die at the iteration boundary, and reverse BFS does not carry liveness across iterations. See §NLL and Iteration Boundaries.
  • [x] Token release order along the ? error-propagation path—Release is driven by scope analysis (retained in ir_gen.rs). At every scope exit point (}, ?, explicit return), live tokens are released in LIFO order. Parent-child relationships in the brand tree automatically handle cascading release. See §? Error Propagation and Scope-Driven Release.
  • [ ] Proof-function syntax (long term, not part of the MVP—does not block any Phase)

References ​


Lifecycle and Disposition ​

StatusLocationDescription
Accepteddocs/design/rfc/accepted/Becomes an official design document