Skip to content

RFC-027a: Explicit Measure for Termination Checking ​

Abstract ​

RFC-027 §7 defines the criterion for termination checking as refinement types (a refinement enters verification mode), while §6.9 specifies the language form of an explicit measure (the built-in predicate Terminates, a core primitive alongside Int and Never). Both are language-design matters belonging to the parent RFC and have been finalized.

This sub-RFC carries these decisions into implementation: how obligations are generated from computation structures, how the decision pipeline is orchestrated, how diagnostics provide direction when inference fails, how measures for mutually recursive functions are shared (SCC optimization), and how error codes are registered. It does not repeat the language semantics; it defines only the mechanisms.

Motivation ​

Why a sub-RFC is needed ​

The criterion (entering verification mode through refinement types) and the form (writing Terminates in a type position) have already been decided in RFC-027 at the language level. The remaining questions are too fine-grained and would bloat the parent RFC:

  • Where obligations come from (recursive call sites, loop back edges, path guards)
  • How to compare a measure that returns a tuple (lexicographic expansion)
  • Whether well-foundedness and strict decrease are two independent obligations or one combined obligation
  • How automatic exploration and explicit measures coexist in the same pipeline
  • How mutual recursion avoids repeatedly writing and verifying the same measure (SCC optimization)
  • How to provide direction when inference fails instead of rejecting the program outright

Trigger ​

This direction was triggered by #318: non-structural recursion (gcd-like non-direct decrease, mutual recursion, merge partitioning) exceeds the template sequence used for measure exploration (all four strategies in RFC-027 §6.2–6.5 take either a “variable of a bounded type” or a “target type + swap operation” as input), and it cannot be rewritten into an analyzable iterative pattern without sacrificing readability. The re-discussion clause in RFC-027’s “Open Questions” section is therefore activated.

Proposal ​

Relationship to automatic exploration ​

An explicit measure is not another pipeline; it is input used after exploration fails. Once a measure has been provided, the same SMT still verifies the same set of obligations; if the measure does not hold, an error is reported with a counterexample. Full automation remains the priority: exploration always runs first, and user intervention occurs only after exploration fails.

This means the two paths share every downstream mechanism—obligation generation, SMT decisioning, lexicographic expansion, and diagnostic formatting all have a single implementation.

Obligation generation ​

For a function f and a measure m, generate two independent obligations, expanded at every recursive call site (including cross-function calls within an SCC):

  1. Well-foundedness: m(args) >= 0—the measure lies over the natural numbers; when the measure returns a non-natural-number type, take the lower bound under the appropriate order on that type. If this cannot be derived from parameter refinements, it enters a residual obligation.
  2. Strict decrease: at every call site, m(callee_args) < m(caller_args), decided under path guards—the guards come from the branch conditions at that call site and reuse RFC-009a path-condition collection.

The two obligations are kept independent rather than combined because their failure directions differ: a well-foundedness failure means the measure’s range is wrong (for example, Int may be negative), while a decrease failure means the recursive arguments are not moving in the expected direction. Diagnostics must distinguish the two so that they can provide the correct checking direction (see “Diagnostics”).

Loops work the same way, replacing “call site” with “back edge”: on every execution path through the loop body, m(next state) < m(current state), with guards taken from the loop condition and branches inside the body.

Lexicographic expansion: when m returns a tuple (m₁, …, mₖ), the obligations are expanded on the obligation-generation side into a disjunctive chain—(m₁' < m₁) ∨ (m₁' == m₁ ∧ m₂' < m₂) ∨ …. The SMT side retains linear fragments and does not depend on native lexicographic support from the solver.

The measure itself must be evaluable at compile time: m must be a function whose evaluation can be proven by constant folding or structural recursion—recursively deferring the termination problem to another unproved function is prohibited (to prevent infinite regression). Pathological measures are caught by the existing E4012 (constant recursion too deep) and structural checks.

Decision pipeline ​

1. 形参递减(结构递归,最强路径,先试)
2. 测度探索:四策略模板序列(RFC-027 §6.2–6.5),找到一个即停止
3. 探索成功 → 生成义务 → SMT 判定 → Proved
4. 探索失败 → 检查类型位是否给出显式测度(Terminates)
     有 → 取该测度生成义务 → SMT 判定
     无 → E4021(终止无法证明,附建议的检查方向)
5. 义务被 SMT 判伪 → E4022(测度不成立,附反例)

Levels 1–3 are RFC-027’s established path; this RFC adds level 4 and two error codes. The entire pipeline runs only when refinement types cause verification mode to be entered (RFC-027 §7)—ordinary types without refinements generate no obligations.

Anchor: unary and binary forms ​

RFC-027 §6.9 defines two arities. This RFC explains their respective implementation sites:

FormAnchorImplementation site
Terminates(m)Name of the enclosing bindingDefault form at the definition site—self-recursive functions and loops
Terminates(FnType, m)Explicit function typeWhen the function type to which the measure belongs must be specified explicitly (the measure is defined elsewhere, or the same measure serves multiple computations)

These are not two constructs, but two arities of the same predicate: a termination obligation always lands on “the computation marked by the type position in which the refinement resides.” Mutual recursion does not require the binary form—each of the two functions can use the unary form, and the shared relationship is identified by SCC (see below).

Implementation status (2026-09-30):

  • The unary form has been implemented, with two observed implementation sites: the function return type position (gcd: (a: Int, b: Int) -> Terminates(b) → key gcd) and the variable binding position (acc: Terminates(n - i) = ... → key acc).
  • The binary form Terminates(FnType, m) is deferred (park). The implementation surface is unary—when Terminates enters the type parser, it is handled as a unary predicate (the first argument is the measure expression), whereas the first argument of the binary form is a function type, requiring an independent parsing path for “which function type the measure belongs to.” There is currently no consumer for it: mutual recursion can be expressed by having each function use the unary form + SCC sharing, and SCC has not yet been implemented, so implementing the binary form first would have no comparable consumer. Condition for proceeding: once SCC has been implemented, if “the same measure serves multiple computations” is still needed, add binary parsing. The gcd form under §Examples in this file (binary) is pending rewriting.

SCC: measure-sharing optimization ​

When a mutually recursive group of functions (a strongly connected component in the call graph) shares the same measure, the obligation on a cross-function edge is m_callee(callee_args) < m_caller(caller_args); when the members share a measure, it reduces to a decrease under the same measure.

This is an optimization, not a prerequisite for correctness: without sharing, each function can write its own measure and close its own verification loop independently and still pass. The value of SCC is to recognize that “this group uses the same measure,” avoiding repeated writing and repeated verification.

A new function-level call graph and SCC collection mechanism is required—the existing TypeDepGraph records type-annotation dependencies between variables (the VC trigger in RFC-027 §6.1); it is a variable-level graph and cannot be reused.

Examples ​

gcd: non-structural recursion ​

yaoxiang
// Measure: an ordinary function, independently testable and reusable
gcd_measure: (a: Int, b: Int) -> Int = { b }

gcd: Terminates((a: Int, b: Int) -> Int, gcd_measure) = {
    if b == 0 { return a }
    return gcd(b, a % b)
}

Obligation generation:

  1. Well-foundedness: gcd_measure(a, b) >= 0, namely b >= 0, follows directly from the parameter refinement NonNegative(b)
  2. Strict decrease: at the sole recursive call site gcd(b, a % b), with path guard b != 0, the obligation is gcd_measure(b, a % b) < gcd_measure(a, b); substituting the measure body expands this to a % b < b
  3. SMT: verify that the negation b != 0 ∧ a % b >= b is unsatisfiable → Proved

Loop: an anonymous construction acquires a denotation ​

yaoxiang
loop: (n: Int) -> Int = {
    mut i: Int = 0
    acc: Terminates(n - i) = while i < n {
        i = i + 1
        i
    }
    return acc
}

The refinement Terminates(m) applies precisely to the value type of the loop body’s tail expression, and the binding name acc supplies the anchor—so the loop can now be referred to, eliminating the “an anonymous construction has no denotation” blind spot. This also explains the unity of the two arities: an obligation always lands on the computation marked by the type position in which the refinement resides; there is no difference between functions and loops.

Pay attention to the tail of the loop body: the value of while is the value of the loop-body block (spec §2.9). If the tail is written as an assignment statement i = i + 1, the block value is Void, and return acc returning Void from -> Int is invalid. The example above adds a tail expression i after the assignment—this is the only correct form, and this document does not provide the erroneous pre-fix form (the pre-fix form and correction record appear under “Implementation Status” below).

Obligation: on the back edge, (n - i') < (n - i), with guard i < n; substituting i' = i + 1 yields 1 > 0, which always holds → Proved.

Implementation status (registered on 2026-10-01; revised on 2026-10-02 and 2026-10-04): the type-side and runtime-side forms of this loop have both been implemented; the zero-iteration value remains a known residue (see “Known Defect D6” below).

The prerequisite is that while have value semantics. This form was blocked for a time—at that time, the while expression was always typed as Void, leaving no value type to carry a refinement, so Terminates could not attach to any computation. This defect has been fixed: according to spec §2.9, “the value of every {} block is given by its tail expression, without exception.” The loop body is also a {} block, so the value of while = the value of the loop-body block.

This rule also exposed an early type error in this example: in the pre-fix form, the loop body’s tail was written as an assignment statement (such as while i < n { i = i + 1 }), so the block value was Void (the same rule in spec §2.9), and return acc returning Void from -> Int was invalid. The correction is to have the tail provide a value: add the tail expression i after the assignment—the example above is already corrected, and this document no longer retains a copyable erroneous form.

The back-edge obligation is structurally identical to the recursive back edge (m[variable := back-edge value] < m), and the loop condition is the source of its well-foundedness lower bound—i < n derives n - i > 0. Testing showed that n - i is Proved—this is a type-side conclusion. At runtime, this form returns 4: the binding receives the body-block value from the last iteration (#409 has been fixed; measured on 2026-10-04). This document’s earlier statement that “n = 4 returns 4” was at that time an unreproduced false conclusion (deleted on 2026-10-02); after issue #409 was fixed, the conclusion became valid, so it has been restored as a reproduced conclusion.

What has been implemented is the function form (unary measure in the return type position, see the gcd example under §Examples) and the loop form, two separate routes. The loop side retains the existing refinement-variable gating + E4021 (the exploration path when there is no explicit measure).

Known Defect D6 (runtime while value; registered on 2026-10-02, fixed on 2026-10-04). Validity on the type side did not necessarily imply runtime usability: in the example above, check reported 0 errors, but at runtime the binding received Void, and any use of that value crashed at runtime. The defect (#409) has been fixed: the runtime value of while (and the isomorphic for) is now the value of the loop body’s tail expression on the final iteration, matching the type-side block_value_ty. In the example above, check reports 0 errors and run exits with 0.

Minimal reproduction (the loop form from §Examples in this file + an explicit main() call at the end—main is not invoked implicitly in script mode). The following code and output are pre-fix historical records, retained as evidence of the defect; with the fix, the same code’s run exits with 0 and produces no output:

yaoxiang
use std.assert

loop: (n: Int) -> Int = {
    mut i: Int = 0
    acc: Terminates(n - i) = while i < n {
        i = i + 1
        i
    }
    return acc
}

main: () -> Void = {
    assert.assert(loop(4) == 4, "循环值应为 4")
}

main()

Measured (binary from this worktree; baseline 2a038f93 reproduces it as well):

error [E6007] Runtime error: type mismatch in comparison Eq: Void vs Int(4)
 --> loop_runtime.yx:14:5
  • Independent of the number of iterations (pre-fix): loop(0) (zero iterations) reports Eq: Void vs Int(0)—the runtime while expression did not produce a value at all; this was not a case of “the last iteration picked the wrong value.”
  • The impact is not limited to the Terminates form (pre-fix): any use of while as a value is affected. Testing x: Int = while i < 3 { i = i + 1; i } and then using x at runtime → Eq: Void vs Int(3). The type-side criterion, obligation generation, and diagnostics are all normal; the defect lies only in the runtime value path.
  • Implemented fix (2026-10-04, issue #409): src/middle/core/ir_gen.rs’s generate_while_expr_ir / generate_iterator_for_loop_ir—before the loop, write an initial Void value to the value register; have the tail expression generated for the loop body write directly to that register; and remove the instruction at the exit that unconditionally overwrites it with Void. Testing showed loop(4) == 4, countdown(3) == 30, x: Int = while i < 3 { i = i + 1; i } (x == 3), and all main-form zero-iteration cases passing.
  • Known residue (zero iterations): when the loop body is never evaluated (such as loop(0)), there is no “body value from the last iteration,” and the value register retains its initial Void—binding it to a non-Void type position and using it at runtime reports an E6007 type mismatch (a loud failure, not a silently incorrect value). This is a static approximation boundary: the type-side block_value_ty gives the type of the body’s tail expression but cannot determine whether the loop executes at least once; downgrading it to Void would break the value type on which this section’s Terminates loop binding relies, so it is not downgraded. The residue contract is pinned by tests/yaoxiang/02-type-system/termination/while_zero_iteration_void_err.yx (// expect: runtime-error E6007).
  • Resolution condition (historical, completed): at runtime, make the value of a while expression produce the value of the loop body’s block tail expression, and ensure that tests/yaoxiang/02-type-system/termination/explicit_termination_measure_loop.yx and while_block_value.yx can pass after adding main() calls. The two corpora now include main() and have been run successfully (explicit_termination_measure_loop.yx’s zero-iteration assertion has been changed to the nonzero-iteration loop(1) == 1; the zero-iteration case has been moved to the new case above).
  • Tracking: issue #409 (runtime while value)—the main form has been fixed and closed; the zero-iteration residue is an intentionally retained design boundary (decision on 2026-10-04, not to be fixed for now), pinned by the contract case tests/yaoxiang/02-type-system/termination/while_zero_iteration_void_err.yx, with no separate tracking item. This section retains the minimal reproduction, fix record, and residue boundary (the English mirror is handled by the automated translation bot and is not edited manually).

Mutual recursion: SCC measure sharing ​

yaoxiang
nat: (n: Int) -> Int = { n }

is_even: Terminates(nat) = {
    if n == 0 { return true }
    return is_odd(n - 1)
}
is_odd: Terminates(nat) = {
    if n == 0 { return false }
    return is_even(n - 1)
}

Each function carries the unary form Terminates(nat). After SCC collection identifies that the two share the same measure, the cross-function-edge obligation nat(n - 1) < nat(n) holds under the guard n != 0, and both functions close their verification loop in one verification pass.

Without SCC recognition, each function independently verifies the same obligation and still passes—merely repeating the work once. This confirms that SCC is an optimization.

Diagnostics ​

When well-foundedness cannot be inferred, do not reject the program outright; suggest a direction to check. This must be distinguished from the diagnostic for a failed decrease obligation: the former points to the measure’s range, while the latter points to the recursive arguments. The three failure classes have the following suggestions:

FailureSuggested direction
Well-foundedness cannot be inferredWhether the measure satisfies a lower bound over its possible values (e.g., whether an Int measure needs >= 0)
Strict decrease is disprovedWhether the recursive arguments really move in the measure’s decreasing direction; include the SMT counterexample
No measure and exploration failedSuggest binding a name to the computation and providing a measure in the type position (RFC-027 §6.9)

Counterexamples are presented according to the RFC-013 diagnostic-message specification. Under nonlinear path guards, a Sat counterexample may be unintuitive—this is recorded as a known limitation and will be iterated on with RFC-013.

Error codes ​

These align with the E4xxx proof-failure family (E4018 refinement predicate violation, E4020 proof function required):

Proposed codeNameTrigger
E4021Termination unprovenExploration failed and the type position contains no explicit measure (suggest providing a Terminates measure)
E4022Measure does not holdThe measure obligation was disproved by the SMT solver (include a counterexample)

The final numbering will follow the actual RFC-013 registry at implementation time (validity of the code range is guaranteed by the build.rs gate).

Existing defects in the diagnostics layer ​

In the current implementation, termination failures within scope are reported as E8001 “internal compiler error” (Unproven is formatted as an ICE)—termination checking is not an ICE, and occupying that code slot both misleads users and hides genuine failures. This RFC corrects that as well: termination failures within scope use E4021/E4022, while the ICE code is returned to genuine internal errors.

Compiler changes ​

ComponentChange
typecheck/layers/termination.rsUnify the interface (the exploration and explicit-measure paths share obligation generation and decisioning); integrate Z3 (production injects default_solver() in checker.rs, while wasm does not inject it; unit tests may inject a stub solver)
Function call graph + SCC (new)The repository has no cross-function call graph—TypeDepGraph is a variable-level type dependency graph and cannot be reused. Create a function-level call graph and SCC collection mechanism for sharing measures across mutually recursive functions
Obligation generationAdd: well-foundedness / strict decrease obligations, path-guard injection, lexicographic expansion
Proof pipeline (RFC-009a / #292)Reuse the ConstExpr → SMTLib chain and operator mappings such as Mod, with no backend changes
util/diagnostic/codes/e4xxx.rsAdd E4021/E4022 registration (through the RFC-013 registry; the build.rs gate takes effect)
locales ×6Templates for the two new codes in six languages
Diagnostics layerMove termination failures within scope out of E8001 and onto the proof-failure family

Backward compatibility ​

  • Programs previously rejected by termination checking but without refinement annotations no longer enter verification mode under the new criterion and compile successfully—an intentional relaxation that only loosens, never tightens, the rules.
  • Programs previously rejected by termination checking and with refinement annotations can pass after a measure is added.
  • Positive structural-recursion cases and existing termination tests: expected output remains unchanged.

Trade-offs ​

Advantages ​

  • Zero new syntax: the measure is written in a type position and reuses the refinement-predicate application mechanism; there is no decreases-style syntax position.
  • Aligned proof-domain behavior: the termination domain adds a fallback channel consistent with the correctness domain, but the implementation site differs—the correctness domain writes an unprovable proposition as a proof function in the body, whereas the termination domain declares a measure that exploration cannot discover in the type position. Both use the same mechanism (both are refinement-type applications).
  • Infrastructure reuse: obligations consist of linear arithmetic plus path guards and use the pipeline connected by #292, with no new backend.
  • Loops acquire a denotation: the binding name serves as the anchor, and loops and functions are completely isomorphic with respect to obligation generation, so no special case for loops is needed.

Disadvantages and risks ​

  • The prerequisite infrastructure is no smaller than mere wiring: a function-level call graph and SCC collection must be created, and Z3 is not yet integrated into the production pipeline. The SCC portion can be deferred (it is an optimization); the call graph shares its source with SCC, so deferring it means mutual recursion must write a separate measure for each function—which still passes, but repeats verification.
  • An explicit measure adds writing burden on low-frequency paths: the two-piece arrangement (measure function + type-position declaration) is more verbose than an inline annotation. This is accepted—the fallback is for low-frequency paths, and in exchange the measure is reusable and independently testable.
  • Noise from well-foundedness obligations: whenever the measure returns Int, >= 0 must be proved. Mitigation: if parameter refinements already provide a lower bound, it is derived automatically; only when it cannot be derived does the case enter a residual obligation, and then only a direction is provided rather than rejection.
  • Counterexample quality: Sat counterexamples under nonlinear guards are unintuitive. This is a known limitation.
  • Terminates is the only predicate for which the compiler writes a body: this departs from the purity of “all predicate bodies can be written by users.” The reason is that its assertions (measure decrease at every call site/back edge) are embedded in the computation structure, and user-written predicates cannot refer to function or loop bodies. The built-in surface is narrowed to one name, with zero new mechanisms.

Alternatives ​

  • Inline annotation syntax (with decreases (b)): an early proposal in this issue, now withdrawn. “Termination checking leaves no annotation-syntax opening” is RFC-027’s final decision; an inline annotation would turn unsupported termination modes into a syntax position rather than a type position, contrary to the worldview that “everything is a YaoXiang function and everything is verified by the type checker.”
  • Standalone proof function (gcd_proof returns Terminates(f, m), discovered by scanning return types): an early design. It has been discarded because it introduces four kinds of complexity: a “discovery mechanism,” a “naming convention,” “selecting the first among multiple candidates,” and “how names inside the proof function body are resolved.” All four arise from placing the proof outside the computation. Moving it into the type position eliminates all four.
  • Only admit the measure into the type (Terminates(m)) and remove the binary form: this is shorter, but loses the means to explicitly indicate measure ownership (when the measure is defined elsewhere or the same measure serves multiple computations). The two arities are two arities of the same predicate, and the cost of retaining them is nearly zero.
  • Provide no fallback and require users to rewrite the program into an analyzable iterative pattern: this is the current behavior. gcd / merge partitioning / mutual recursion cannot be rewritten without sacrificing readability—and that is precisely the condition that triggers the re-discussion clause.

Non-goals ​

  • No new syntax/keyword/annotation position.
  • Do not generalize automatic measure synthesis (the four strategies remain RFC-027’s established plan; beyond that scope, use an explicit measure). General measure inference belongs to the undecidable “discovery” side; only template boundaries can be stipulated, and completeness cannot be promised.
  • Do not jointly solve propositions borrowed from RFC-009a (each is decided independently while sharing the backend).
  • Do not perform totality checking at the dependent-type level.
  • Do not require the measure to return a natural-number type (do not pursue Lean’s WellFoundedRelation type-class mechanism)—the measure’s return type is unrestricted, and well-foundedness is an independent obligation delegated to refinement inference or the SMT solver.

Stages and acceptance ​

  • [x] Obligation generation: well-foundedness / strict decrease, path-guard injection
  • [x] Explicit-measure wiring: unary-form anchor resolution (return type position / binding position) + type-position measure extraction
  • [x] SMT decision wiring (reuse the #292 pipeline; inject Z3 into the production pipeline—the previous injection point had never been called)
  • [ ] Function-level call graph + SCC collection (measure-sharing optimization). Condition for proceeding: a need appears for “the same measure serves multiple computations” or avoiding repeated verification of mutual recursion
  • [ ] Lexicographic expansion (when the measure returns a tuple). Condition for proceeding: a real use case appears with a tuple-returning measure
  • [x] E4021/E4022 registration + six-language locales (three-way consistency: codes ↔ locales ↔ RFC-013 code table)
  • [x] Diagnostics-layer correction: termination failures within scope are moved out of E8001 and onto the proof-failure family. E4021 already exists; E4022 goes through the user domain via DisproofKind::MeasureNotDecreasing, with a test case pinning that it must not be downgraded to an ICE
  • [x] E2E positive cases: gcd (including the “residual obligation does not reject” form), structural recursion with no regressions
  • [x] E2E negative cases: measure does not hold → E4022 (with counterexample); no measure → E4021
  • [x] E2E positive case (loop, type side): the type decision for the Terminates(n - i) binding form holds (D5 resolved)
  • [x] E2E positive case (loop, runtime): runtime while value (D6 fixed, #409, 2026-10-04)—explicit_termination_measure_loop.yx and while_block_value.yx pass after adding main() and running them
  • [ ] E2E residue (zero iterations): while used as a value produces Void when the loop body executes zero times (static approximation boundary). Contract case 02-type-system/termination/while_zero_iteration_void_err.yx (// expect: runtime-error E6007); see “Known Residue” in the loop example under §Examples for the condition for proceeding
  • [ ] E2E pending: is_even-is_odd mutual recursion (awaiting SCC)
  • [ ] Binary form Terminates(FnType, m) (park). See §Anchor for the condition for proceeding
  • [ ] Return-position multi-parameter predicate + symbolic arguments (an explicit diagnostic has existed since 2026-10-02, but support is still missing). See §Implementation Landing Record (2026-10-02, this hardening round) for the trigger form, alternative, and condition for proceeding
  • [x] Criterion regression: recursion and loops without refinement annotations are no longer rejected by termination checking; obligations continue to be triggered when refinement annotations are present
  • [x] Acceptance demonstration: write a declaration whose measure does not hold → compilation fails with a readable counterexample (measure_not_decreasing_err.yx); after correcting it, it passes (measure_decreasing.yx)
  • [x] Return-point refinement (2026-10-02): return-position formal parameters are identified by declaration name, and predicate arguments are genuinely substituted into constraints; undeclared free variables report E1001
  • [x] Termination strategy 1 restored (2026-10-02): candidates are no longer cleared by boundary filtering, and measure changes are inferred according to Direction; added flag loops (strategy 1b)
  • [x] Documentation and implementation alignment (2026-10-02): the first loop example and landing record in this document, the two loop examples in language-spec/type-system.md, the §2.15 → §2.9 reference correction, and RFC-011’s loop example

Implementation landing record (2026-09-30 ~ 2026-10-01) ​

Implemented surface: unary Terminates enters the type parser → AST measure extraction (not through lossy MonoType conversion, which would discard the measure as Int(64)) → obligation generation (recursive call sites and loop back edges, with path guards) → two SMT decisions for well-foundedness and strict decrease → diagnostic emission.

There are two gates for emitting E4022 (both only under-report and never produce false positives):

  1. Disproof rather than an inability to decide—the error is emitted only when the solver provides a counterexample (Sat); Unknown means “cannot decide” and is handled according to “give direction, do not reject” under §Trade-offs.
  2. Measure well-foundedness has been proved—integer < is not well-founded, so a measure that does not decrease does not imply nontermination (gcd still terminates when b is negative). If well-foundedness has not been proved, the error is not emitted even when decrease is disproved; the case enters a residual obligation.

These gates resolve the apparent contradiction between “give direction, do not reject” and “report a disproof”: well-foundedness is the permit that licenses the inference “not decreasing implies nontermination.”

Existing defects fixed along the way (all serving as foundations for this RFC):

  • Predicate definition not registered (#377-3): substitution of predicate bodies in PredicateResolver had long been implemented, but it was short-circuited by an empty table. After registration was added, refinement constraints could be reasoned about symbolically for the first time—the premise for well-foundedness b >= 0.
  • No value semantics for while: see the loop example under §Examples.
  • Evaluator missing Neg/Pos/BitNot: inconsistent with the same-named implementation in const_eval, preventing negative literals such as -5 from folding to constants on all paths that use the evaluator.

Implementation landing record (2026-10-02, this hardening round) ​

Four workstreams, each corresponding to actual changes; every item below is a reproducible measured conclusion (commands and outputs are given with each item), not a statement of plans.

1. Return-point refinement: formal parameters identified by declaration name + predicate arguments genuinely substituted into constraints ​

Before the fix (baseline 2a038f93), there were three deviations: the predicate arguments of -> (r: P(r + 100)) were discarded, degrading to P(r); in -> (r: Eq2(m, r)), the undefined m was silently substituted with the return value, degrading the constraint to a tautology. Fix: the parser preserves a single named parenthesis as NamedParen (carrying the declared name), and the type checker recognizes only that name as the return-value formal parameter; every other out-of-scope free variable is reported individually as E1001, and the return-point obligation is abandoned. Measured:

CaseBeforeAfter (measured)
d1: () -> (r: IsPositive(r + 100)) = { return -5 }E4018 (constraint computed as -5 > 0)0 error (constraint -5 + 100 > 0 holds)
d2: () -> (r: IsPositive(r - 100)) = { return 5 }Silently passeserror [E4018] (constraint 5 - 100 > 0 is disproved, with counterexample)
g: () -> (r: Eq2(m, r)) = { return 7 } (m undefined)Silently passeserror [E1001] Unknown variable: 'm'

2. Return-position multi-parameter predicate + symbolic arguments: explicit diagnostics (known gap, unsupported) ​

  • Trigger form (minimal example):

    yaoxiang
    SumUpTo: (n: Int, s: Int) -> Type = { s == n * 2 }
    f: (b: Int) -> (r: SumUpTo(b, r)) = { return b * 2 }

    Measured diagnostic: error [E2031] After assigning to 'f', the refinement type constraint of 'r': SumUpTo(b, (b * 2)) cannot be statically proven in the proof kernel—the target is the return position ('r'), no longer the formal parameter name 'b' to which it was mistakenly attached before the fix; the constraint text gives the form after substituting the actual arguments.

  • Reason: the proof kernel only executes proof-function calls whose arguments are all computable values (literals / already-bound variables); a multi-parameter predicate containing variables cannot obtain a call in the return position, so it reports an error when it cannot decide.

  • Alternative form (the diagnostic’s help gives both options): change the arguments to compile-time-foldable literals (such as SumUpTo(3, r)), or provide a proof function for the predicate that returns Type and participates in compile-time execution.

  • Condition for proceeding: the proof kernel supports argument substitution for “multi-parameter predicate + symbolic arguments” (the same substitution path as the preceding item).

  • Tracking: no new issue—this section is the sole tracking location.

3. Termination strategy 1 restored (defects a / b of #377) ​

  • Defect a: strategy 1’s boundary inputs were cleared by the filter “a boundary must be a loop invariant” → candidates were always empty. Fix: strategy 1 now consumes the unfiltered boundary set, with soundness enforced by verifying each assignment.
  • Defect b: the change direction of candidate measures was written incorrectly (m' was always constructed as v + 1) → the decision always failed. Fix: the direction is determined by the boundary operator (Lt/Le ⇒ Increasing, Gt/Ge ⇒ Decreasing), and the measure change is inferred according to Direction (Increasing Δm = δbound - δv; Decreasing Δm = δv - δbound); Δm >= 0 is rejected on the synthesis side and never reaches the solver.
  • New flag loop (strategy 1b): bare boolean condition + clearing a flag inside a threshold guard + a variable moving unconditionally toward the threshold on every iteration; the measure is the “distance to the threshold.”
  • Soundness criterion unchanged: prefer reporting “unable to prove” over falsely proving termination—the measure variable’s advance must be unconditional (at the top level of the body); boundary displacement takes the most unfavorable end including the guard; unknown displacement is rejected; rebinding the measure variable inside a guarded block is also rejected.

Measured (binary from this worktree):

CorpusMeasured
02-type-system/termination/rank_function_dual_variable_loop.yx (i < j { i += 1; j -= 1 })0 error
02-type-system/termination/flag_loop_guarded_exit.yx0 error
06-compile-errors/termination/termination_unproven_err.yxStill error [E4021]
4 counterexample corpora (guard-block rebinding / unknown-displacement rebinding, etc.)All error [E4021]

4. Documentation and implementation alignment ​

The first loop example under §Examples in this document and this implementation landing record, the two loop examples in docs/src/reference/language-spec/type-system.md, RFC-011 §Termination Checking’s loop example, and the correction of the §2.15 → §2.9 reference—details are available in the diffs of the respective documents (§2.15 is “Scope”; the block-value rule is in §2.9 “Block Expressions”).

5. Still not implemented after this round ​

SCC collection, lexicographic expansion, the binary form Terminates(FnType, m), mutual-recursion E2E, the runtime while zero-iteration residue (the D6 main form is fixed), and return-position multi-parameter predicates + symbolic arguments—all remain unchecked entries under §Stages and Acceptance, with their conditions for proceeding stated in each entry.

  • #318 (the issue that initiated this RFC), #251 (parent milestone P1)
  • RFC-027 (host: §7 refinement-type criterion, §6.1–6.5 four measure-exploration strategies, §6.9 explicit measure, §Open Questions re-discussion clause)
  • RFC-009a / #292 (shared SMT pipeline and path-condition collection—foundational prerequisites)
  • RFC-013 (error-code registry and proof-failure semantic family)