RFC-027: Compile-Time Predicates and Unified Static Verification
References:
- RFC-009: Ownership Model
- RFC-010: Unified Type Syntax - name: type = value Model
- RFC-011: Generic System Design
- RFC-024: Concurrency Model Based on spawn Blocks
Supersedes: RFC-022: Hoare Logic Static Verification Support (Specification Comments and Specification Types) — Deprecated
Abstract
This RFC proposes introducing compile-time predicates into YaoXiang as first-class citizens and unifying all compile-time static verification into a single proof pipeline. Compile-time predicates are not bolted-on specification comments—they are functions. A function that returns Type can be used in type position; the compiler invokes it at compile time and checks its return value. Types are propositions, and compile-time evaluation is proof.
Core thesis: the sole job of type checking at compile time is to construct and verify proof terms. Type equalities, token conflicts, dependent-type reduction, compile-time predicate evaluation, and Hoare-logic implication are all different kinds of type checking within the same compile-time proof pipeline. They share one pipeline and one proof kernel, Kernel::check. Proof terms and propositions inhabit the same unified term world (RFC-039); propositions receive their meaning from a logic signature, LogicSignature, while proof terms are represented by certificates, Certificate. Relative to a signature, a certificate is verified only by the kernel according to the rules of that signature. SMT solvers, tactics, and proof search are all untrusted certificate producers: their only responsibility is to find certificates. unsat is not Proved. When the kernel returns Unproven, the programmer writes a YaoXiang proof function as explicit evidence—it is a proof term, and the kernel verifies it in exactly the same way that it verifies the return type of any function. Everything is YaoXiang code, and everything is verified by the proof kernel.
Motivation
Why Was RFC-022 Deprecated?
RFC-022 designed specifications in the form of //! comments:
max: (T: Ord) -> ((arr: Array(T, n)) -> T) = {
//! requires: NonEmpty(n) = n > 0 ← This is a comment independent of the type
//! ensures: ExistsMax(result, arr[0..n]) ← This is a comment independent of the type
}This commits a fundamental error of the Curry–Howard correspondence: it splits specifications and types into two layers. Comments are not types. Comments do not participate in type checking. Comments embody the mental model of an “external tool.”
The white paper states this clearly:
“There are no
//!comments. There is no separate specification language. Everything is inside the type system.”
Current Problems
- The
//!comments of RFC-022 are external syntax independent of the type system - Specification types and ordinary types form two separate systems, causing conceptual redundancy
- The split between verifying in Debug builds and ignoring verification in Release builds breaks the model’s unity
- In conventional understanding, SMT solvers are positioned as external tools or as a means of “trusting Z3’s unsat”—YaoXiang instead positions them as untrusted certificate producers: they produce candidate certificates, which are verified by the proof kernel
- Type checking, borrow checking, compile-time predicate checking, and macro expansion each follow different paths
The Right Mental Model
Type checking can be abstracted as a function:
Kernel::check(signature, certificate, proposition) → Proved | Disproved(Model) | UnprovenAll compile-time checks—simple type matching, borrow-conflict detection, and compile-time predicate verification—are subtasks of this function. They share one proof pipeline and differ only in the complexity of the proof terms and the strategy used to construct them.
Every obligation carries the currently effective LogicSignature. When the kernel returns Unproven, the programmer supplies explicit evidence: a proof function whose return type equals the proposition to be proved serves as the certificate. The kernel verifies it with the same signature—this is the same operation as ordinary type checking. Signatures are replaceable: changing the signature changes the set of inference rules, but neither the kernel nor the three-valued result changes (§4.1).
Proposal
1. {} Is the Proof Space: Types Are Assertions, and Verification Is Type Checking
The {} of YaoXiang is the compile-time proof space. Everything inside it is an assertion, and the proof kernel guarantees under the current LogicSignature that every item has a verifiable certificate—either automatically found by a producer or supplied explicitly by the programmer (§4.3).
Point: Type = { x: Float, y: Float }
# ^^^^^^^^^^^^^^^^^^^^^ The compiler guarantees that x is Float and y is Float
List: (T: Type) -> Type = { data: Array(T) }
# ^^^^^^^^^^^^^^^ The compiler guarantees that data is Array(T)Generics are a special case of compile-time predicates.
Positive: (x: Int) -> Type = { x > 0 }
# ^^^^^^ ^^^^^^
# Parameter at the signature Only assertions inside {}
# The compiler verifies x > 0 when invoked at compile time
List: (T: Type) -> Type = { data: Array(T) }
# ^^^^^^^^ ^^^^^^^^^^^^^^^
# Parameter at the signature The compiler verifies type_of(T) == Type and type_of(data) == Array(T)The pattern is always the same: name: (params) -> Type = { assertions }. The compiler does not distinguish “type assertions” from “value assertions”—both are evaluation targets in the proof pipeline.
Loop invariants do not need to be written separately. Type annotations on variables are Floyd–Hoare invariants.
SumUpTo: (arr: Array(Int), i: Int) -> Type = { s: Int; s == sum(arr[0..i]) }
UpTo: (n: Int) -> Type = { i: Int; 0 <= i <= n }
sum: (arr: Array(Int)) -> Int = {
mut s: SumUpTo(arr, i) = 0 # The annotation refers to i—it tells the compiler that the type of s depends on i
mut i: UpTo(arr.len) = 0 # During initialization i=0; verification: 0 == sum(arr[0..0]) → True
while i < arr.len {
s += arr[i] # The compiler verifies: s_new == sum(arr[0..i+1])
i += 1 # Changing i triggers re-verification of the s dependency: s satisfies SumUpTo(arr, i_new)
}
return s # s: SumUpTo(arr, arr.len) = sum(arr[0..arr.len])
}The compiler generates one verification condition for the loop body—the induction hypothesis (the type annotation) → the assignment operation → whether the new value satisfies the type annotation. Once the producer produces a candidate certificate for the inductive step and Kernel::check verifies it, all iterations are covered automatically. There is no need for : decreases, : Invariant, or an inductive proof—the induction is decomposed into local VCs for each assignment.
2. Preconditions/Postconditions: Compile-Time Predicates on Parameter and Return Types
Abandon RFC-022’s //! requires///! ensures. Compile-time predicates become type annotations on parameters or return values.
On the parameter side, this is a function call. A compile-time predicate is a function that returns Type, so its use on the parameter side is a call to it—exactly like factorial(5). The return-value side introduces a new concept: a return-value formal parameter.
# Precondition: explicitly invoke a compile-time predicate in the parameter type
Positive: (x: Int) -> Type = { x > 0 }
divide: (a: Int, b: Positive(b)) -> Int = a / b
# ^^^^^^^^^^ b is the current formal parameter name and is passed to Positive
# The compiler extracts the actual argument value at the call site, substitutes it for b, and verifies Positive(actual)
# Example: divide(10, 2) → verify Positive(2) = { 2 > 0 } → True
# Example: divide(10, 0) → verify Positive(0) = { 0 > 0 } → False → compilation error
# Postcondition: return-value formal parameter + compile-time predicate
IsMax: (T: Ord, arr: Array(T), result: T) -> Type = {
forall j in 0..arr.len: result >= arr[j]
}
NonEmpty: (arr: Array(T)) -> Type = { arr.len > 0 }
max: (T: Ord) -> ((arr: NonEmpty(arr))) -> (result: IsMax(T, arr, result)) = {
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# result is a return-value formal parameter; its value is supplied by return
# The compiler substitutes the return value at the return site and verifies the postcondition
candidate = arr[0]
for i in 1..arr.len {
if arr[i] > candidate { candidate = arr[i] }
}
return candidate
}Key rules:
- Parameter side:
b: Positive(b)—bis the current formal parameter name and is passed toPositive. This uses ordinary function-call syntax, with no implicit behavior. - Return side:
-> (result: IsMax(T, arr, result))—resultis a return-value formal parameter, and its value is supplied by areturnstatement.resultexists only in the type signature and is only referenced by predicates; it does not enter the function-body scope and does not appear at call sites. - The return-value formal parameter is optional: when there is no postcondition, it is omitted and the signature is identical to that of an ordinary function (
-> Int). - Uniformity: parameters and return-value formal parameters are the same concept—
formal_parameter_name: predicate_call(actual_argument)—with the only difference being whether the value is supplied by the caller or byreturn.
Implementation note (2026-10-02): recognition of a return-position formal parameter strictly follows the declared name—the
rin-> (r: P(...))is the sole return-value formal parameter. Any other free variables in the constraint that are not in scope are not substituted with the return value; instead, an undefined-identifier error is reported (observed:g: () -> (r: Eq2(m, r)) = { return 7 }(mis undefined) →error [E1001] Unknown variable: 'm'). The arguments of a predicate call are substituted into the constraint according to the actual arguments:P(r + 100)becomes “return value + 100,” not “return value.”Known gap (2026-10-02): multi-parameter predicates with symbolic arguments in return position are not yet supported. Triggering form:
f: (b: Int) -> (r: SumUpTo(b, r)) = { return b * 2 }(SumUpTo: (n: Int, s: Int) -> Type = { s == n * 2 }) →error [E2031] … the refinement type constraint of 'r': SumUpTo(b, (b * 2)) cannot be statically proven. Workaround: replace the argument with a compile-time-foldable literal (for example,SumUpTo(3, r)), or provide a proof function returningTypefor that predicate; the condition for removal is that the proof kernel support argument substitution for “multi-parameter predicates + symbolic arguments.” See RFC-027a §Implementation Notes (2026-10-02, this hardening round).
3. Path-Condition Propagation: Compile-Time Verification of Runtime Values
When a compile-time predicate is used in a binding position, its arguments are supplied explicitly by the programmer. When a runtime value enters a refinement-type parameter, the producer collects path conditions and produces a candidate certificate, which Kernel::check verifies under the current LogicSignature—there is no need for the programmer to pass proof implicitly. Explicit evidence is a first-class form used when proof must be supplied (§4.3).
3.1 Explicit Function Calls
When a compile-time predicate is used in a binding position, its arguments are supplied explicitly by the programmer—this is simply a function call, with no implicit behavior.
Positive: (x: Int) -> Type = { x > 0 } is a compile-time predicate constructor. When it appears in a binding position (a parameter declaration, variable declaration, or return type), the programmer explicitly supplies an already-bound variable name:
b: Positive(b)
// b has already been declared as the current formal parameter; Positive(b) is a function call
// After normalization: b: { b > 0 }The compiler does not need to fill in parameters implicitly—b: Positive(b) is a function call just like f(5). b is bound as a parameter name, and its type annotation Positive(b) refers to itself. This is the standard dependent-type pattern, not an implicit expansion rule.
Unification with RFC-010 self: RFC-010 established that self is not a keyword but merely a conventional parameter name (“writing p, this, or x has exactly the same effect”). b: Positive(b) uses the same mechanism—the parameter name can be referenced in a type annotation. self appears in the position self: Point, while b appears in the b: Positive(b) position. Both type annotations refer to the parameter itself. The only difference is the complexity of the type annotation; the mechanism is exactly the same—once a name is bound, the type may depend on that name.
Return types likewise use explicit function calls:
Sorted: (arr: Array(T)) -> Type = { forall i in 0..arr.len-1: arr[i] <= arr[i+1] }
sort: (arr: Array(T)) -> (result: Sorted(result)) = { ... }
// ^^^^^^^^^^^^^^^^^^^^^^^
// result is a return-value formal parameter; Sorted(result) is a function call
// The compiler substitutes the return value for result at the return site and verifies Sorted(return value)The same applies to local-variable declarations:
let x: Positive(x) = 5
// x is bound to 5, Positive(5) → { 5 > 0 } → True → passes
// let y: Positive(y) = 0
// y is bound to 0, Positive(0) → { 0 > 0 } → False → compilation error3.2 Path-Condition Collection
When a runtime value appears in a conditional branch, the compiler automatically collects path conditions, forming the current scope’s assumption set. These assumptions participate in verification as background knowledge for compile-time Bool evaluation.
if y > 0 {
// The compiler automatically obtains the assumption in this branch: { y > 0 }
let result = divide(x, y)
// Verification condition: (y > 0) ⇒ (y > 0)
// The proof pipeline determines that the implication holds → Proved
} else {
// Assumption in this branch: { !(y > 0) }
// If divide(x, y) is called, the verification condition is !(y > 0) ⇒ y > 0
// The proof pipeline determines that the implication does not hold → Disproved
}This is not a hard-coded special mode in the compiler—it is the natural behavior of the compile-time proof pipeline. At each type-checking call site, the pipeline receives:
{背景假设} ⇒ {验证目标}The proof pipeline determines entailment. Proved → pass; Disproved → compilation error + counterexample; Unproven → compilation error + unsolved proposition. Background assumptions come from the path conditions at the current program point.
3.3 Assumption Stack
While analyzing control flow, the compiler maintains an assumption set for each basic block:
- if guard:
if y > 0→ the true branch pushesy > 0, and the false branch pushes!(y > 0)(if an else is present) - match pattern:
if let Some(v) = opt→ the branch pushesopt == Some(v) - logical conjunction:
if x > 0 and y < 10→ the branch pushesx > 0andy < 10 - function precondition: when calling
divide(a, b), evidence thatbsatisfiesPositivemust come either from the current assumptions or from a refinement-type annotation on the argument itself (bhas already been annotated asPositive, so its type carriesb > 0) - assignment: when
let z = yis executed, the refinement conditions already attached toyare propagated toz
All assumptions enter the context field of Certificate (Γ) and are handed to Kernel::check along with the candidate certificate; only when the producer needs SMT does it translate the same Γ into SMT-LIB background assertions.
3.4 Compilation Error When No Static Evidence Exists
If the programmer directly writes:
divide_user_input: (x: Int, y: Int) -> Int = divide(x, y)The current program point has no y > 0 assumption, and the argument y itself has no Positive type annotation. The verification condition is:
{} ⇒ { y > 0 }The pipeline returns Disproved (the implication does not hold) → compilation error:
Unable to prove that argument
bsatisfiesPositivein the call todivide.ycomes from the function input and has no proven bound. Consider guarding the call with an if branch:if y > 0 { divide(x, y) }.
YaoXiang does not permit a runtime value to enter a refinement-type parameter directly without static evidence. This is not a restriction—it is at the core of the hard-safety philosophy: no code for which Kernel::check cannot verify a certificate under the current signature may pass compilation.
3.5 Relationship to the Unified Pipeline
Path-condition propagation is not an additional mechanism. It is a direct extension of the compile-time proof pipeline into control-flow analysis:
| Stage | Responsibility |
|---|---|
| Path-condition collection | During compiler control-flow analysis, annotate each basic block with an assumption set |
| Verification-condition generation | When a type constraint requiring verification is encountered, combine path conditions + argument type information |
| Proof-pipeline verdict | The certificate producer produces a candidate certificate → Kernel::check(signature, certificate, proposition) → three-valued result |
| Result | Proved → pass; Disproved → compilation error + counterexample; Unproven → compilation error + unsolved proposition + evidence-supplementation prompt |
There are no new components and no special rules. Path conditions are the local assumption set Γ of a LogicSignature; they share the same pipeline and the same budget system as type equalities and borrow constraints.
4. Proof Kernel: Kernel::check
All compile-time checks share one pipeline and one proof kernel. The kernel’s sole verdict entry point is:
Kernel::check(
signature : LogicSignature,
certificate : Certificate,
proposition : Proposition,
) -> CheckVerdict<Certificate>check is a pure function: given the same signature, certificate, and proposition, it always returns the same result; it does not read solver state, the clock, or file paths. It does exactly one thing—replay the derivation steps of the certificate according to the rules of the signature, checking that each step’s rule instance, premises, context, and substitution are valid, and verifying that the final conclusion is exactly the proposition. The kernel does not search, guess, or complete certificates; a certificate missing a step, using the wrong rule, or reaching a mismatched conclusion must not produce Proved.
This is the same picture as the unified term world of RFC-039: type positions and value positions share the same compile-time terms; the proposition Proposition, the proof term Certificate, and the sorts/rules/axioms in the signature are all terms from this one world. Definitional equality (§12.1) is a pure decision, the q=0 evidence obligation (RFC-011 §4.1) is a call-site obligation, and the Σ witness (§13) is a construction-site obligation—all three flow into the same check rather than opening separate trust channels.
The three values of CheckVerdict<Certificate> are consistent with §4.1: Proved(checked) carries a kernel-verified certificate, Disproved(model) carries a counterexample, and Unproven carries the unsolved proposition and a reason. Only Proved(checked) can satisfy an obligation; checked is the certificate that can be cached and incrementally reused at compile time.
编译期义务(命题 + 当前 LogicSignature)
│
├── producer 编排(都不可信,见 §8)
│ ├── 内核直判规则:结构等价、βδι-归约、令牌活性事实
│ ├── Γ 等式桥 / 调用侧 q=0 证据(RFC-011 §4.1)
│ ├── 显式证据:证明函数、axiom library / proof library 条目
│ └── SMT / tactics / proof search:产出候选 Certificate
│
▼
Kernel::check(signature, certificate, proposition)
│ 按 signature.rules 重放每一步;不用「unsat」顶替检查
▼
┌──────────────────────────────────────────────┐
│ Proved(checked) → 编译通过(证书编译期留存)│
│ Disproved(model) → 编译错误 + 反例 │
│ Unproven → 未解命题 + 原因 + 补证据 │
└──────────────────────────────────────────────┘
│
▼
Unproven → 提示补显式证据(证明函数 / 换签名 / 补公理)
│
▼
再次 check ──→ Proved(checked) ──→ 编译通过4.1 CheckVerdict: Three-Valued Algebra and Logic Signatures
check returns three results—an inevitable consequence of the halting problem and a natural partition of proof theory:
CheckVerdict<C> = Proved(checked: C) | Disproved(model: Model) | Unproven(reason, subject)Proved(checked)→ halts; the certificate has been verified step by step undersignature, and its conclusion equalsproposition. The obligation passes;checkedis the certificate that can be cached at compile time (§13).Disproved(model)→ halts; a counterexamplemodelexists. Compilation error + counterexample + source location.Unproven(reason, subject)→ within the current signature, evidence, and resource limits, the producer did not deliver a verifiable certificate. Compilation error + unsolved proposition + reason + evidence-supplementation prompt (the diagnostic shape in §12.3).
Unproven ≠ False. The kernel saying “cannot determine this” is not equivalent to the proposition being false—it means only that there is no certificate that passes verification under the current signature and current evidence set. This is honesty, not a defect.
The logic signature LogicSignature determines “what counts as a valid derivation step.” It is replaceable data:
LogicSignature {
sorts : Map<SortName, SortDecl> // 项与命题的类别
rules : Map<RuleId, InferenceRule> // 内核可重放的推导规则
axioms : Map<AxiomId, Proposition> // 本签名接受的公理
libraries : [LibraryRef] // 全部 axiom/proof 库,见下
hash : ContentHash // 覆盖 sorts/rules/axioms + libraries 全部条目
}
LibraryRef {
kind : LibraryKind // Axiom | Proof
id : LibraryId // 库内条目 id 的命名空间
manifest : Manifest // 条目 id + 命题/规则形态 + 来源
hash : ContentHash // 对 manifest 规范字节的内容哈希
}
SortDecl {
space : SortSpace // Proof | Data,见下
arity : [SortName] // 该 sort 构造子接受的实参 sort
}
SortSpace = Proof | DataEach SortDecl in sorts has a space; it is the sole criterion for whether an application of a type family is a proposition or data. space = Proof means that inhabitants of the sort are proof terms (the results of propositions, refinement types, or proof families), while space = Data means that inhabitants are runtime data (Int, Array, Vec, ordinary records). Pos (refinement predicates such as { v > 0 }), Assert, Terminates, and proof/type families returning space=Proof all have space=Proof; data type families such as Array: (T: Type, N: Int) -> Type have space=Data. space is registered by a library manifest or predicate declaration; it is not inferred from field names, argument shapes, or syntax that merely “looks like a predicate.” The evidence classification in §14.1 reads only this field. A data type family remains a data field even if it depends on a strictly preceding field.
libraries is a list: one signature may use multiple axiom libraries and multiple proof libraries simultaneously—for example, the built-in linarith axiom library + a user zfc-core axiom library + the std-proofs proof library + project-private proof libraries. Each library carries its own kind, id, manifest, and hash. Every entry in axioms belongs to a kind=Axiom library by LibraryId, while proof-library entries belong to a kind=Proof library by LibraryId. signature.hash covers sorts/rules/axioms and every entry in libraries (not merely one); adding or removing any library, or changing even one byte of any manifest, changes the signature and invalidates cache keys, certificates, and incremental reuse.
sorts,rules, andaxiomsare the body of the signature; every entry inaxiomsmust belong to amanifestentry of somekind=Axiomlibrary inlibraries. A certificate that references an axiom not registered by any library ⇒checkrejects it.- Every
LibraryRefinlibrarieshas its own manifest and content hash: the manifest lists entry IDs, proposition/rule shapes, and provenance, whilehashis computed over the canonical bytes of the manifest;kinddistinguishes axiom libraries from proof libraries. The signaturehashcoverssorts/rules/axiomsand allLibraryRefentries (not two). - Built-in libraries (
Intlinear arithmetic,Arraylength, theAssertbridge, etc.) are also ordinaryLibraryRefentries inlibraries, merely distributed with the compiler; they coexist with user and project libraries and are not hard-coded trust roots in the kernel. Trust derives from “this signature and itslibrarieslist were adopted by this compilation,” not from the name of a library or solver.
Signatures are replaceable, and replacement means replacing data rather than replacing the kernel:
| Signature | sorts / rules values | Typical use |
|---|---|---|
| Classical arithmetic fragment | Linear-arithmetic sorts + no quantifier rules | x > 0, 0 <= idx < arr.len |
| Classical first order (with excluded middle) | Classical sequent rules + excluded-middle axiom | Classical implication, proof by contradiction |
| Constructive | Constructive rules, no excluded middle, no double-negation elimination | Witness extraction, avoidance of non-constructive proofs |
| ZFC fragment | Set-theory sorts + registered choice/extensionality axioms | Propositions requiring set-theoretic vocabulary |
Proved is always relative to a signature: the same proposition may be Proved under a classical signature and Unproven under a constructive one. A certificate carries signature_hash; check first verifies that the hashes agree and then replays it; a mismatch directly produces Unproven, without attempting “roughly compatible” reuse.
Cross-signature use must be explicit. Let A/B be two signatures, P a proposition in A, and certA a certificate verified under A. To use the conclusion under B, there are exactly three legal paths, each of which must leave an inspectable trace:
- Translation term: provide
translate: A.Proposition → B.Propositionand a certificate for it verified underB; obtainQ = translate(P), then proveQunderB. - Bridging axiom: register an explicit bridging axiom in a
kind=Axiomlibrary inB.libraries(for example, “the corresponding rule ofAhas a corresponding interpretation on the relevant sort ofB”), and have the certificate reference(LibraryId, AxiomId);B.hashchanges with that registration. - Reproof: construct a new certificate directly for
PunderB.
An implicit transfer of the form “Proved under A ⇒ Proved under B” is never allowed, nor is it allowed to reuse certA under a different signature hash. Cross-module export of Σ (§13) and the cross-module form of q=0 evidence follow these same three paths.
A hard budget limit is the engineering solution to the halting problem (the numerical values appear in §8.4). There is no knob—offering one would amount to asking users, “Do you think your program will halt?” Neither users nor the compiler know. Exhausting the budget yields Unproven(reason=BudgetExceeded), not Disproved.
4.2 Certificate: A Signature-Relative Proof Term
A certificate is the compile-time representation of a “proof term” and has meaning only relative to a LogicSignature:
Certificate {
signature_hash : ContentHash // 必须等于 signature.hash
proposition : Proposition // 结论,统一项世界里的项
steps : [ProofStep] // 按 signature.rules 的推导序列
evidence_refs : [EvidenceRef] // 显式证据的引用
}
ProofStep {
rule : RuleId // 必须命中 signature.rules
premises : [StepId | AxiomId | GammaId | EvidenceId]
context : Γ // 局部假设(路径条件、等式桥、q=0 证据)
conclusion : Proposition
subst : Substitution // 项替换,统一项世界的项
}
EvidenceRef = ExplicitProof(AstNodeId) // 证明函数 / 用户写的显式证据
| LibraryAxiom(LibraryId, AxiomId)
| LibraryProof(LibraryId, ProofId)
| ProducerHint(bytes) // SMT/tactics/proof search 的提示,不直接信任check performs four mechanical checks on every ProofStep: ① rule exists in signature.rules; ② premises point to earlier steps, registered axioms, Γ facts, or explicit evidence, and each can be resolved; ③ after applying subst to the rule pattern, it is identical to conclusion (equality is decided by the pure decision procedure in §12.1); ④ the final step’s conclusion is identical to certificate.proposition. If any check fails ⇒ Unproven, and the kernel identifies the failing step; it never skips these four checks because the producer says “unsat.”
ProducerHint is only a hint: a producer may attach it to a candidate certificate—for example, an SMT-LIB script, model, or tactic trace—but the kernel neither executes it nor treats it as a rule. Hints merely serve to “complete a candidate into inspectable steps.” If completion fails, the result remains Unproven.
4.3 After Unproven: Supplying Explicit Evidence (Proof Functions Are First-Class)
When the kernel returns Unproven, diagnostics must prompt the user to supply evidence, rather than rendering “cannot determine this” as “this is false” (for the diagnostic shape, see §12.3). Legal forms of evidence are treated as “first-class”—they are proof terms in the unified term world, not bolt-on features:
- Proof function: a YaoXiang function whose return type equals the proposition to be proved. It is an
ExplicitProof(AstNodeId), and the kernel verifies it through exactly the same mechanism used to verifyadd(a, b): Int. - axiom library entry: an axiom registered in the signature,
EvidenceRef::LibraryAxiom. - proof library entry: a named proof (reusable, independently testable, and supplied with a manifest hash),
EvidenceRef::LibraryProof. - Existing kernel certificate: a certificate already verified as
Proved(checked)under the samesignature_hash, reused directly or used as a premise. - Change signature / add axiom / write a translation term: explicitly register one of the cross-signature paths in §4.1, then run
checkagain.
命题 = 类型(统一项世界里的 Proposition)
证明 = 程序(该类型的一个值,即 Certificate 的 steps)
验证 = Kernel::check(signature, certificate, proposition)
信任 = 该签名被本次编译采用 + 证书逐步可重放;不来自求解器If a candidate certificate produced by SMT/tactics/proof search cannot be completed into steps, it falls back to Unproven—the programmer supplies explicit evidence, or asks the producer to try another search path. No AI is needed, no export to Coq is needed, and no new concept is needed.
# Proposition: a refinement property that the compiler cannot prove automatically
FirstIsMin: (T: Ord, arr: Sorted(T)) -> Type = {
forall i in 0..arr.len: arr[0] <= arr[i]
}
# Explicit evidence: the programmer writes a function whose return type is the proposition above
# The kernel verifies it—exactly as it verifies add(a,b): Int
first_is_min: (T: Ord, arr: Sorted(T)) -> FirstIsMin(T, arr) = {
...
}A property that cannot be proved automatically at compile time → the programmer supplies explicit evidence (a first-class proof term) → the kernel verifies it under the signature. The entire process is a smooth gradient—the producer finds simple certificates for you, leaving your effort for the difficult ones.
4.4 Layered Dependencies Within the Pipeline
The producers above share the same Kernel::check interface, but they have an orchestration order. Type equalities are prerequisites for all subsequent analyses; ownership/token checks depend on type information; refinement-predicate verification depends on the results of the preceding two layers. The compiler orchestrates the layers, and an expression that fails at a lower layer does not enter a higher layer—this avoids wasting search budget on programs with type errors; the conclusion of every layer must still be verified by check; the layer order merely determines which candidate certificate is requested first from a producer.
编排顺序(同一内核,分层调度)
├── 第 0 层:类型等式(T1 == T2)
│ └── 内核直判规则(defeq)→ 产出候选证书 → check
├── 第 1 层:所有权/令牌冲突
│ └── 流敏感活性事实 → 产出候选证书 → check
└── 第 2 层:精化谓词/霍尔蕴含
└── producer(Γ 证据 / proof library / SMT 搜索)→ 候选证书 → checkEvery layer still returns Proved/Disproved/Unproven and shares the same interface, the same signature, and the same budget system.
5. Unification of the Three Function Layers
| Layer | Execution time | Input | Output | Example |
|---|---|---|---|---|
| Value-level function | Runtime | Value | Value | add: (a: Int, b: Int) -> Int = a + b |
| Type constructor | Compile time | Type/value | Type | List: (T: Type) -> Type = { data: Array(T) } |
| Compile-time predicate | Compile time | Value | Type | Positive: (x: Int) -> Type = { x > 0 } |
All use the same name: type = value syntax. Compile-time predicates and type constructors follow the same compile-time proof pipeline—{} is the proof space.
6. Loops: Floyd–Hoare Verification-Condition Generation
Loops do not need separate : Invariant(...) or : decreases(...) annotations. Compile-time predicate type annotations on variables define Floyd–Hoare-style assertions—the compiler derives verification conditions from those annotations, and the proof pipeline checks whether each assignment preserves the type.
The core mechanism is that every assignment corresponds to a Hoare triple {P} x := e {Q}, whose verification condition is P ⇒ Q[e/x]. The compiler generates one verification condition for the loop body—once the proof pipeline verifies the inductive step, all iterations are covered automatically.
SumUpTo: (arr: Array(Int), i: Int) -> Type = { s: Int; s == sum(arr[0..i]) }
UpTo: (n: Int) -> Type = { i: Int; 0 <= i <= n }
sum: (arr: Array(Int)) -> Int = {
mut s: SumUpTo(arr, i) = 0 # The annotation refers to i; during initialization i=0; verification: 0 == sum(arr[0..0]) → True
mut i: UpTo(arr.len) = 0 # Verification: 0 <= 0 <= arr.len → True
while i < arr.len {
# The compiler generates one VC for the loop body. Premises: s satisfies SumUpTo(arr, i), and i satisfies UpTo(arr.len).
#
# s += arr[i]:
# Verification obligation: s_new satisfies SumUpTo(arr, i) (the current i is unchanged)
# Substitute s_new = s_old + arr[i]:
# Need s_old + arr[i] == sum(arr[0..i+1])
# From the induction hypothesis s_old == sum(arr[0..i]), add arr[i] to both sides:
# sum(arr[0..i]) + arr[i] == sum(arr[0..i+1])
# Compiler + SMT: linear arithmetic, milliseconds → Proved
#
# i += 1:
# Changing i → the dependency graph shows that the type annotation of s refers to i → triggers re-verification
# New verification target: s satisfies SumUpTo(arr, i_new)
# That is, s == sum(arr[0..i_new]), guaranteed by the previous step → Proved
s += arr[i]
i += 1
}
return s # At this point s: SumUpTo(arr, arr.len), that is, s == sum(arr[0..arr.len])
}A loop invariant is simply a type annotation on a variable—the programmer writes the type, and the compiler checks the inductive step. The compiler does not need to “discover” the invariant or “perform induction automatically”—it decomposes the inductive proof into local verification conditions for each assignment and hands them to the proof pipeline to be handled by divide and conquer.
6.1 Dependency Tracking: Dependent Types on Mutable Variables
The mechanism above requires the compiler to know that the type annotation of s, SumUpTo(arr, i), refers to i—when i changes, the type constraint of s changes with it. This requires the compiler to maintain a type-dependency graph between variables.
Data structure:
TypeDepGraph: Map<VarName, Set<VarName>>
# The key is the depended-on variable; the value is the set of variables whose type annotations refer to that variable
# Example: { i: {s}, j: {s, t}, ... }Construction: while processing mut v: Pred(... x ...) = init, the type checker resolves free-variable references in the arguments of Pred(...). If an argument refers to another mutable variable x in the current scope, the dependency graph records x → v.
Trigger: when the depended-on variable x is assigned, the compiler:
- Finds all variables
{v₁, v₂, ...}in the dependency graph that depend onx - For each
v, generates a verification condition: does the current value ofvsatisfy the updated typePred(... x_new ...)? - Sends the VC to the proof pipeline
Assignment-order sensitivity: dependency tracking naturally enforces the correct assignment order. Taking SumUpTo(arr, i) as an example:
# Correct order
s += arr[i] # s_new satisfies SumUpTo(arr, i+1)
i += 1 # Changing i → re-verify that s satisfies SumUpTo(arr, i_new) → True
# Wrong order—the compiler rejects it
i += 1 # Changing i → re-verify that s satisfies SumUpTo(arr, i_new)
# s has not yet been updated, so s_old == sum(arr[0..i_old]) ≠ sum(arr[0..i_new])
# → Compilation error: variable s does not satisfy type SumUpTo(arr, i_new)
s += arr[i] # UnreachableComposite dependencies: a variable may depend on several variables. A type annotation such as { v: Int; v == x + y } depends on both x and y—a change to either triggers re-verification.
Relationship to the proof pipeline: dependency tracking is the trigger for VC generation, not an independent verification mechanism. It answers “when must a VC be generated?”—the proof pipeline answers “does the VC hold?”
7. Termination Checking
Scope: refinement types. Termination is not an independent switch; it is part of a verification mode: once a type is refined (Refined { base, constraint }), the computation it annotates enters verification mode, and that mode requires termination. Ordinary types that have not been refined do not enter verification mode and generate no termination obligations.
This yields two corollaries:
- Loops: a bare
whiledoes not enter verification mode; a measure variable with a refinement annotation (such asi: UpTo(n)) enters verification mode and requires proof of termination. - Recursion: a function signature with a refinement (a refined parameter or a refined return type) enters verification mode and requires proof that the measure strictly decreases at every recursive call site.
Automation has priority within the mode: the compiler first explores measures automatically and passes those it can prove; if exploration fails and no explicit measure has been supplied, compilation fails. There is no annotation-syntax escape hatch—the measure and termination proposition are both written in type position, introducing no new syntax such as decreases. For the forms of measures and explicit fallbacks, see §6.9.
6.1 Design Principles
The compiler automatically extracts the information needed for a termination proof from two places:
- Variable type annotations: bounds in refinement types (for example,
UpTo(n)supplies the upper boundnand lower bound0) - Loop-body operations: the operation applied to variables on each iteration
The compiler tries four measure-synthesis strategies in priority order and stops as soon as one succeeds. The four strategies are a restricted template sequence for measure exploration. Their input consists of refinement constraints (strategies 1–4 all start from “a variable of bounded type”), not “compile-time-evaluated code”; they are the automatic and manual sides of the same thing as the explicit measures in §6.9.
Measure exploration is exploration, not inference. Exploration enumerates only templates (linear rank, violation count, bounded patterns, multiplicative scaling) and does not guarantee that a solution exists—general measure inference is undecidable (it reduces to the halting problem). Cases outside the templates must therefore be supplied explicitly by the programmer (§6.9), or compilation fails.
6.2 Strategy 1: Automatic Synthesis of a Linear Rank Function
When a variable has a linear-bound annotation, the producer enumerates candidate linear measures and produces candidate certificates for the decrease obligations, which Kernel::check verifies.
输入:
变量 v₁: UpTo(u₁), v₂: UpTo(u₂), ...(有上下界的变量)
循环条件 cond
循环体中的赋值集合
算法:
1. 从类型标注提取每个变量的界:[low_i, high_i]
2. 枚举候选度量:v_i, u_i - v_i, v_i - v_j, 等线性组合
3. 对每个候选度量 m:
- 产出 m ≥ 0 的候选证书(从类型界推导)→ check
- 对循环体的每条执行路径,产出 m' < m 的候选证书 → check
4. 找到符合条件的线性组合 → 终止得证Coverage: loops in which any variable is assigned a linear expression (v = a·v + b) and has a bounded type annotation. This includes i += const, i -= const, and interval contraction in binary search:
# Binary search: low = mid + 1 or high = mid
# The measure high - low strictly decreases on both paths
binary_search: (arr: Sorted(Int, arr), key: Int) -> Option(Int) = {
mut low: UpTo(arr.len) = 0
mut high: UpTo(arr.len) = arr.len
while low < high {
let mid = (low + high) / 2
if arr.data[mid] < key { low = mid + 1 }
else if arr.data[mid] > key { high = mid }
else { return Some(mid) }
}
return None
}6.3 Strategy 2: Predicate Violation Count—Automatically Extracting a Measure from the Target Type 【Experimental Strategy】
⚠️ Current status: experimental strategy; during Phase 3 implementation, decide whether to include it based on practical feasibility. This strategy works for adjacent-swap operations (bubble sort, insertion sort), but cannot automatically prove termination for non-adjacent operations (quick-sort partition, heap-sort sift-down). The coverage boundary appears in the table below. If Phase 3 validation shows it infeasible, this strategy will be removed or deferred as future work.
Core insight: the specifications written by the user are material for compiler reasoning. The compiler does not need a built-in definition of “what it means to be sorted”—it reads the definition of Sorted and automatically extracts a measure from it.
输入:
目标类型:Sorted(arr) = { forall i in 0..arr.len-1: arr[i] <= arr[i+1] }
循环体操作:相邻元素交换
算法:
1. 解析谓词定义:forall i in range: cond(i, arr)
2. 自动生成度量:violation_count = |{ i | ¬cond(i, arr) }|
3. 分析操作对度量的影响:
- 相邻交换 arr[j], arr[j+1] = arr[j+1], arr[j]
- 只影响索引 j-1, j, j+1 三对
- 如果 arr[j] > arr[j+1](违反谓词),交换后这对满足谓词
- violation_count 至少减 1
4. 上界:n·(n-1)/2(最大相邻逆序数),下界:0
→ 终止得证Current coverage:
| Algorithm | Operation pattern | Provable by Strategy 2? | Reason |
|---|---|---|---|
| Bubble sort | Adjacent swap | ✅ | violation_count strictly decreases with each swap |
| Insertion sort | Adjacent movement | ✅ | Each shift eliminates one violating pair |
| Selection sort | Non-adjacent swap | ❌ | A single swap may increase violation_count |
| Quick sort | partition | ❌ | Non-adjacent swap; monotonic decrease is not guaranteed |
| Heap sort | sift-down | ❌ | Tree-shaped operation; violation_count is not monotonic |
Complementary strategies: for quick sort, the low < high interval contraction can be covered by Strategy 1 (linear rank function)—the outer partition recursion halves the interval each time. Strategies 1 and 2 provide complementary coverage, and most practical algorithms can be proved by one of them. Generalizing Strategy 2 (non-adjacent operations, tree-shaped operations) remains an open problem.
sort: (arr: Array(Int)) -> (result: Sorted(result)) = {
mut i: UpTo(arr.len) = 0
while i < arr.len - 1 {
mut j: UpTo(arr.len - i - 1) = 0
while j < arr.len - i - 1 {
if arr.data[j] > arr.data[j+1] {
arr.data[j], arr.data[j+1] = arr.data[j+1], arr.data[j]
}
j += 1
}
i += 1
}
return arr
}6.4 Strategy 3: Bounded Increasing/Decreasing Patterns
For v += const (a positive constant), with an upper-bound type annotation on the variable → the measure upper_bound - v decreases by const each time, with lower bound 0. This is a degenerate case of Strategy 1, which the compiler handles first as a fast path.
6.5 Strategy 4: Multiplicative-Scaling Measure Template
For v *= const (const > 1), with upper- and lower-bound type annotations on the variable. The compiler has a built-in logarithmic measure template ceil(log_const(upper/v)); multiplying by const decreases the measure by 1.
mut i: Positive(i) = 1
while i < n {
# The compiler automatically derives the measure ceil(log₂(n/i)); multiplying by 2 decreases it by 1
i *= 2
}6.6 Separation of Termination and Correctness
Termination proof and correctness proof are independent:
- Termination: the four strategies above automatically prove that a loop exits in finitely many steps; when exploration fails, the programmer supplies a measure in type position (§6.9)
- Correctness: whether the loop body makes progress toward the target type, checked by the compile-time proof pipeline through verification conditions
If both pass → compilation passes. If termination is proved but correctness fails → compilation error + counterexample. If correctness is proved but termination cannot be proved → compilation error identifying the variable or operation that could not be analyzed. If both fail → compilation error reports the two failure reasons separately.
6.7 Termination Checking for Recursive Functions
For recursive functions with refinement signatures, the compiler checks that formal parameters decrease at every recursive call site:
gcd: (a: Int, b: NonNegative(b)) -> Int = {
if b == 0 { return a }
return gcd(b, a % b) // The compiler explores: the well-founded-order measure of (b, a % b) decreases → termination
}Formal-parameter decrease is the strongest automatic path (structural recursion). When exploration fails, the programmer explicitly supplies a measure in type position (§6.9).
6.8 Hard Boundary
For i = f(i), where f is not invertible, not closed, and preserves no monotonicity—automatic proof of termination is mathematically impossible. Compilation error:
This loop cannot automatically be proved to terminate. The loop variable depends on the unanalyzable function
f. Use an iteration pattern that the compiler can analyze, or bind a name to this loop and supply a measure in type position (§6.9).
This is not a compiler failure. No code that cannot be statically proved safe may pass compilation. Even when an explicit measure is supplied, one certificate verified by Kernel::check must be provided for decrease and another for well-foundedness—an incorrect measure is rejected with a counterexample. Humans may fail to prove something, but they cannot prove it incorrectly.
6.9 Explicit Measure: Terminates
When automatic exploration cannot find a measure, the programmer writes the measure in type position—the same mechanism as Positive(b) and IsMax(T, arr, result) (a predicate application), with no new syntax:
// Measure: an ordinary function; independently testable, reusable, and absent at runtime
gcd_measure: (a: Int, b: Int) -> Int = { b }
// The termination component grows on the function's own type position
gcd: Terminates((a: Int, b: Int) -> Int, gcd_measure) = {
if b == 0 { return a }
return gcd(b, a % b)
}
// Loop: the binding name is the anchor; the measure obtains the in-scope quantity by name
loop: (n: Int) -> Int = {
mut i = 0
acc: Terminates(n - i) = while i < n {
i = i + 1
i
}
return acc
}The rationale for the loop case is that Terminates(m) refines the value type of the loop-body tail expression, and the binding name acc provides the anchor. The loop can therefore be denoted, eliminating the “dead corner” in which an anonymous construction has no name.
The body tail must yield a value: the value of a loop = the value of the loop-body block (§2.9), and the value of a block = its tail expression. If the body tail is an assignment statement (such as
{ i = i + 1 }), the block value isVoid, andreturn accwould returnVoidfrom-> Int, so the types would not agree. This example therefore explicitly writesias the body tail. This does not change the measure’s semantics—the measuren - iis a state expression, independent of the loop’s value type.
Implementation note (registered 2026-10-02; updated 2026-10-04): the type-side behavior of this section’s loop example is valid (
checkreports 0 errors, and the back-edge obligation is Proved). The runtime-value defect (#409) has been fixed: awhileused as a value now takes the value of the body block’s tail expression on the loop body’s final iteration, matching the type-sideblock_value_tycriterion—loop(4) == 4andcountdown(3) == 30hold in actual execution (with the same fix forfor).Known residual issue (zero iterations): when the loop body is never evaluated, there is no “body value from the final iteration,” so the loop value is still
Void—binding it to a non-Voidtype position and using it at runtime reportsE6007 Runtime error: type mismatch in comparison Eq: Void vs Int(0)(a loud type mismatch, not a silently wrong value). This is a static-approximation boundary: theblock_value_tycriterion yields the type of the tail expression, but it has no ability to determine “whether the loop executes at least once” (which would require data-flow/provability analysis), so the type side does not silently degrade (degradation would break the value type on which this section’sTerminatesloop binding depends). The residual behavior is pinned by the corpustests/yaoxiang/02-type-system/termination/while_zero_iteration_void_err.yx(// expect: runtime-error E6007). This residual issue has been confirmed as an intentionally retained design boundary (decision of 2026-10-04; not currently being fixed), so issue #409 has been closed with the main form fixed and will not be tracked separately. See the minimal reproduction and historical impact in RFC-027a §Examples, Loop section, “Known Defect D6.” In addition: termination Strategy 1 (linear rank function) is active again in this round, so the order “write an explicit measure only after automatic exploration fails” remains unchanged— an explicit measure is still a fallback after exploration fails.
Terminates is a built-in predicate, belonging to the same core primitives as Int and Never. It is the only predicate whose function body is generated by the compiler—its assertion (“the measure strictly decreases at every recursive call site / loop back edge”) is embedded in the computational structure, and user-written predicates cannot refer to the function body or loop body, so it cannot be expressed using the predicate-definition syntax in the “Syntax” section. The built-in surface is therefore reduced to this single name.
Arity. Terminates(FnType, m) and Terminates(m) are two arities of the same predicate, not two different constructs:
| Form | Anchor | Use |
|---|---|---|
Terminates(m) | Name of the enclosing binding | Self-recursive functions and loops—the default form |
Terminates(FnType, m) | Explicit function type | Cases such as mutual recursion where the anchor is not unique |
The two are essentially the same: the termination obligation always lands on “the computation annotated in the type position of the refinement.”
A measure does not constrain the return type. A measure may be an expression of any type (it is not required to be a natural number); its “strict decrease” is determined by the well-founded orders available on that type. Whether the measure is well-founded—for example, whether an Int-valued measure is >= 0—is an independent obligation, just like the decrease obligation. A producer produces candidate certificates for both and hands them to Kernel::check for verification; when neither can be derived, diagnostics do not reject directly but instead suggest what to check (whether the lower bound holds and whether recursive parameters actually move in that direction).
Relationship to automatic exploration: an explicit measure is not a separate pipeline; it is input supplied after producer exploration fails. After the measure is supplied, the producer still produces candidate certificates and hands the same Kernel::check the decrease and well-foundedness obligations; if they do not hold, compilation fails with a counterexample.
For obligation generation, the decision pipeline, diagnostic directions, and the measure for mutual recursion (SCC), see RFC-027a: Explicit Measure for Termination Checking.
8. Certificate Producers: SMT / Tactics / Proof Search Are All Untrusted
SMT solvers, tactic scripts, and proof-search processes all play the same role in this design: certificate producers (certificate producers). They are untrusted: the compiler does not treat their return values as proofs, only as hints for “finding a candidate certificate.” The only trusted component is Kernel::check(signature, certificate, proposition) (§4).
8.1 Trust Model
- The kernel is the verifier:
checkreplayscertificate.stepsaccording tosignature.rules(§4.2). It does not invoke solvers, parseunsat, or read producer logs. - The producer is the searcher: given a
signatureand aproposition, the producer makes a best effort to deliver aCertificate. Whatever it returns or claims does not constituteProved. - Forbidding
Unsat ⇒ Proved:unsatsays at most that “no countermodel was found under the producer’s own translation and theory.” It is neither a certificate nor a guarantee thatcertificate.stepsexists. Mappingunsatdirectly toProvedis equivalent to outsourcing the trust root to the solver, directly conflicting with the pure-function kernel in §4. This RFC explicitly forbids that mapping. satis also not sufficient forDisproved:sat + modelis merely a candidate counterexample supplied by the producer; it must become a falsification certificate thatKernel::checkcan decide (replayed according to the signature’s falsification rules, or computed by a kernel-direct rule showing that “the two sides differ after normalization”; see §12.1) beforeDisproved(model)can be returned. Translation distortion (for example, integer-literal fidelity, issue #561) can causesatto carry a spurious model; trusting it directly would falsely reject valid programs.unknown/ timeout / budget exhaustion ⇒Unproven: the diagnostic includes the unsolved proposition, reason, and evidence-supplementation prompt (§12.3), and must not be degraded to an internal compiler error (E8001).
8.2 Data Flow from Producer to Kernel
proposition + signature
│
▼
┌───────────────────────────────────────────────┐
│ certificate producer(不可信) │
│ · 内核直判规则(结构等价、βδι、defeq) │
│ · Γ 等式桥 / q=0 证据(RFC-011 §4.1) │
│ · axiom library / proof library 条目 │
│ · 证明函数(显式证据,§4.3) │
│ · SMT-LIB 2.6 / Z3 / CVC5 │
│ · tactics / proof search │
└───────────────────────────────────────────────┘
│ 候选 Certificate(steps 可能为空 / 只带 ProducerHint)
▼
Kernel::check(signature, certificate, proposition)
│
├── steps 齐备且逐步合法、结论同一 → Proved(checked)
├── 证伪证书经 check 确认(或内核直判)→ Disproved(model)
└── 证书缺步 / 规则未登记 / 哈希不符 → Unproven(补证据提示)Producers may run in parallel, may cache results, and may switch backends; none of this freedom changes the single requirement to “deliver a replayable certificate.” SMT-LIB 2.6 remains the translation target (an ISO standard natively supported by Z3 / CVC5 / MathSAT / Yices), with Z3 as the default backend, CVC5 as an alternative, and compile-time switching—SMT-LIB is an input format for producers, not a trust boundary. There is no “general-purpose solver abstraction layer,” and no “general-purpose producer abstraction layer”: a producer has exactly one output contract, “deliver a Certificate.”
8.3 From unsat to a Legal Certificate: Registering Translation Rules
For unsat to become useful, the producer’s theory must first be folded into rules registered in signature. For example, the manifest of a kind=Axiom library in libraries may register a set of linarith rules for the linear-arithmetic fragment (including their applicable sorts and premise shapes); an SMT-LIB unsat result is expanded by a proof-producing adapter into a sequence of ProofSteps for those rules and then handed to check. The adapter is itself an untrusted producer: its steps are still replayed one by one.
This requirement changes “trust Z3’s unsat” into “trust that the linarith rules are registered in the signature and that the certificate is inspectable step by step.” Translation bugs are no longer papered over by the hope that “some other test will expose them”—if the adapter produces a certificate with missing steps or incorrect rules, check immediately returns Unproven. An unsat result for an unregistered theory must never enter the Proved path.
Before the proof-producing adapter lands, a conservative degradation is permitted: the arithmetic fragment uses kernel-direct rules (structural equivalence, constant folding, βδι-reduction) and registered proof-library entries; the producer’s unsat is attached only as a ProducerHint to the candidate certificate and does not independently trigger Proved. The degraded surface is smaller than trusting unsat outright, and there is no silent pass.
8.4 Budgets (For Producers, Not the Kernel)
Budgets constrain producer search; they do not constrain the correctness of check—check is deterministic replay, and its step count is determined by the certificate length.
| Budget dimension | Default | Description |
|---|---|---|
| Search steps | 10,000 | Maximum number of solver/search steps for a producer; exceeding it returns Unproven |
| Time | 100ms | Maximum search time per obligation |
| Quantifier instantiation depth | 3 | Nested-quantifier depth translated by the producer |
| Certificate replay steps | Hard limit | Maximum steps.len() for check; exceeding it ⇒ Unproven |
Exceeding the budget returns Unproven, producing a compilation error + predicate location + a one-line budget summary (§12.3). There is no degradation, no runtime check, and no silent pass. Dependent-type pre-reduction (factorial(5) → 120, append([1,2],[3]) → [1,2,3]) is handled by kernel-direct rules and consumes no producer budget.
8.5 Relationship to the Three-Valued Result, Γ, and q=0 Evidence
Constant-equality facts in Γ (§12) and the four sources of q=0-slot evidence (RFC-011 §4.1: literals, value environments, single-value pinning, and Γ equalities) are all sources that a producer may reference through EvidenceRef; they do not form another decision path. §3.5’s statement that “path conditions are background knowledge” is refined here to mean that “path conditions are the local Γ context of the signature, handed to check together with the context field of the Certificate.”
8.6 Current Implementation Gap: predicate.rs Trusts SMT Outright
The design in this section is inconsistent with the current production implementation. The gap is recorded honestly rather than pretending that it has already landed:
- In
src/frontend/core/sema/layers/predicate.rs,try_implicationmapsSMTResult::Unsatdirectly toSome(Ok(()));try_smt_solvemapsSMTResult::Unsatdirectly toOk(()).Ok(())is theProvedarm ofProofResult—this is trustingunsatoutright, with noCertificateconstructed or replayed. SMTResult::Sat { model }in the same file directly constructsProofFailure::Disproved, and the counterexample is not verified by the kernel under the signature; translation distortion (issue #561) can falsely reject valid programs.ProofContext(src/frontend/core/sema/proof/context.rs) currently carries onlyenv / assumptions / dep_graph / budget / dep_envand has noLogicSignaturefield;ProofFailureandProofResultare three-valued results, but there is noCertificatetype.- The current pipeline is therefore “the producer’s return value = the verdict,” whereas the target pipeline is “the producer delivers a certificate →
Kernel::check→ verdict.” These are not differences in wording but differences in trust model: the former treats Z3’s result as the trust root; the latter treats the signature and kernel as the trust root. - Direction of the fix (code is not provided in this RFC): ① introduce
LogicSignatureandCertificaterepresentations and carry the current signature inProofContext; ② converttry_implication/try_smt_solveinto “produce a candidate certificate,” withunsatused only as aProducerHint; ③ makeKernel::checkthe sole exit toProved, and confirmSatcounterexamples throughcheckas well; ④ register translation rules such aslinarithas described in §8.3. Implementation proceeds under the “evidence enforcement / complete Π/Σ” phase of RFC-039; this round defines only the contract.
8.7 wasm and Backend Differences
When Z3 is unavailable under wasm (the SMT code is excluded by cfg(not(target_arch = "wasm32"))), the producer has one fewer search path and degrades to Unproven (conservative, with fewer reports). This is unrelated to “whether the signatures agree”: under the same signature, native has one more producer candidate while wasm has one fewer, and the behavior of Kernel::check is exactly the same. The existing native/wasm difference table (§Open Questions) is now interpreted as “producer availability,” not “decision precision.”
Programmers do not need to know that SMT exists. The mental model is: the compiler passes when it can verify a certificate under the current signature; otherwise it reports Unproven and prompts for evidence—if an automatic producer cannot find one, write a proof function (a first-class form of explicit evidence) and let the kernel inspect it.
9. Composing Compile-Time Predicates
Compile-time predicates are functions that return Type, and composition is naturally implemented through function composition:
SortedNonEmpty: (T: Ord, arr: Array(T)) -> Type = {
Sorted(T, arr) and NonEmpty(arr)
}10. Code Examples
9.1 Safe Division
Positive: (x: Int) -> Type = { x > 0 }
divide: (a: Int, b: Positive(b)) -> Int = a / b
result = divide(10, 2) # ✅ The compiler verifies Positive(2) = { 2 > 0 } → True
# result = divide(10, 0) # ❌ The compiler verifies Positive(0) = { 0 > 0 } → False9.2 Safe Array Access
InBounds: (idx: Int, arr: Array(T)) -> Type = { 0 <= idx and idx < arr.len }
get: (arr: Array(T), idx: InBounds(idx, arr)) -> T = arr.data[idx]
arr = Array(Int)(1, 2, 3)
x = get(arr, 1) # ✅ The compiler verifies InBounds(1, arr) = { 0 <= 1 and 1 < 3 } → True
# y = get(arr, 5) # ❌ The compiler verifies InBounds(5, arr) = { 0 <= 5 and 5 < 3 } → False9.3 Sort Correctness
Sorted: (T: Ord, arr: Array(T)) -> Type = {
forall i in 0..arr.len-1: arr[i] <= arr[i+1]
}
sort: (T: Ord) -> ((arr: Array(T))) -> (result: Sorted(T, result)) = {
result = arr.clone()
# ... sort implementation ...
return result
}9.4 Loops: Compiler VC Generation
SumUpTo: (arr: Array(Int), i: Int) -> Type = { s: Int; s == sum(arr[0..i]) }
UpTo: (n: Int) -> Type = { i: Int; 0 <= i <= n }
sum: (arr: Array(Int)) -> Int = {
mut s: SumUpTo(arr, i) = 0
mut i: UpTo(arr.len) = 0
while i < arr.len {
s += arr[i]
i += 1
}
return s
}11. dispatch Routing Pipeline: Unified Compile-Time and Runtime Dispatch
Implementation note (registered 2026-10-03, #377-2): the semantics of this section are valid and connected to production, but the structure is not a standalone
layers/dispatch.rsmodule. Production routing is implemented through three call-site obligations inchecker.rs—binding-site re-verification (revalidate_refined), call-site arguments (check_call_arg_refinements), and the return-position postcondition (check_return_refinement). Two of these directly calllayers::predicate::check_predicate: call-site arguments and return-position postconditions share the sole decision unitjudge_refined_obligation(checker/refinement.rs), whereasrevalidate_refinedhas its own E2030 semantics. A fourth obligation surface exists in the proof executor (proof_execution.rs, wired on 2026-11-14, issue #537): when executing a proof call, it first expands the called proof function’s own parameter refinements (RFC-027 §3.3 nested obligations for call-site preconditions—a breadth-first worklist, a deduplication set, and §8 budget closure; closed Bool constraints judged false produce E4018, while Call forms are enqueued for continued execution). The originallayers/dispatch.rshad zero production call sites, and its handling ofUnproven { ProofFunctionRequired }was “downgrade to a W1080 warning and inject Γ,” which conflicts with the production implementation (Unprovenalways reports an error; seerefined_unproven), so the entire module was deleted. Also note: the “insert a runtime check” action in the Runtime row of the table in this section has no emission point in production (RuntimeOutcome::InsertCheckhas no consumer), while Γ injection is performed independently by branch guards inownership.rsand byinference/expressions.rs.
assert and Assert are two sides of the same refinement-type primitive. The dispatch pipeline, dispatch, automatically chooses between compile-time proof and runtime checking according to whether the predicate’s free variables are accessible at compile time:
| Criterion | Mode | Behavior |
|---|---|---|
| All free variables are known at compile time (generic parameters, compile-time constants) | CompileTime | Enter the proof pipeline: the certificate producer delivers a candidate certificate → Kernel::check → Proved erases / Disproved is a compilation error / Unproven prompts for evidence |
| Some free variables come from runtime (function parameters, external input, mut variables) | Runtime | Insert a runtime check and inject the refinement fact into the flow-sensitive assumption set Γ |
The key point: “cannot decide” ≠ “disproved.” In CompileTime mode, Unknown requires proof (there is no silent degradation); in Runtime mode, the proposition has no truth value at compile time at all—no matter how strong the prover is, it cannot write a universally true proof for “the user might supply a negative number,” so a runtime check is the only sound choice. This is not a matter of the prover being insufficient; it is a theoretical necessity.
12. Flow-Sensitive Assumption Set Γ: Strongest Postcondition Propagation
The compiler maintains a flow-sensitive assumption set Γ that tracks the propositions known to hold at each control-flow point.
SP (strongest-postcondition) propagation:
assert(x > 0) // Γ = {x > 0}
y = x + 1 // Γ = {x > 0, y > 1} ← SP propagationKill set for mut variables: after a mut variable is reassigned, all assumptions involving that variable are removed from Γ:
assert(x > 0) // Γ = {x > 0}
mut x = x - 5 // Γ = {} ← x > 0 is killedThis is a hard soundness requirement—when a variable’s value changes, old assumptions no longer hold.
Branch merging: when IF/ELSE or match branches are merged, Γ takes the intersection of the branch assumptions. Only propositions that hold on every path are carried out of the branch.
Equality bridge (automatic evidence for the q=0 slot): constant-equality facts in Γ are a legal source of evidence for compile-time value parameters (RFC-011 §4.1, q=0 slots). Within the guard branch of if y == 42 { f(y)(y) }, Γ records y == 42 ⇒ y is treated as 42 in the q=0 slot, and the call is checked along the existing f(42) path. One side of the equality must be a compile-time constant; filling the q=0 slot with a runtime value that has no equality evidence is still reported at the call site. This is not a new mechanism—the verification condition {y == 42} ⇒ {y ≡ 42} uses the existing implication decision procedure.
12.1 Definition of Definitional Equality (defeq)
This section was added by RFC-039: the equality bridge above supplies a source of evidence for the q=0 slot, while this section completes the definition of equality itself, the role of Unproven in type equality, and the diagnostic shape.
Equality is the sole equivalence relation on types. It is defined by exactly one rule: after each side is normalized, they are identical.
- Normalization consists of three kinds of reduction: δ unfolds type aliases and definitions; β reduces type families and dependent-type applications; ι normalizes literal types—the identity of a literal type is determined only by its value, not by its source spelling (
03and3are the same type). - Identity is fully structural: type constructors have the same name, and arguments are identical one by one. Equality does not read cache keys, rendered text, or perform any reasoning about refinement predicates.
- Subtyping is an independent relation:
A <: Bis decided by the subtyping rules; the simultaneous truth ofA <: BandB <: Adoes not define equality. Bidirectional subtyping would mix covariance and interface duck-typing rules into equivalence, contaminating the notions of “assignable” and “equivalent.” - Different
Refinedpredicates ⇒ Unproven: when the base types are the same but the predicates differ, the compiler returns Unproven, not Disproved. Predicate equivalence belongs to the assumption-set Γ layer (the equality bridge above and the Γ equality rules that follow); until that layer lands, the compiler can only say “cannot determine this.”
The failure surface of equality is consistent with the three-valued algebra in §4.1: both sides normalize successfully and are identical ⇒ Proved; both sides normalize successfully but differ ⇒ Disproved; either side fails to normalize ⇒ Unproven (budget exhaustion or a capability boundary). A failed reduction does not produce Disproved—inability to compute does not mean inequality.
Equality is a pure decision: it does not bind type variables; success means acceptance and leaves no instantiation. Decision points (assignment, arguments, and return positions) first use unification; after unification fails, they may switch to equality, but must first roll back any partial bindings produced by the unification attempt. Without rollback, an attempt judged non-equivalent would leave bindings behind and pollute subsequent inference.
12.2 Unproven ≠ False: Type Equality
The three-valued algebra of §4.1 applies to every obligation point, and type equality is one of them. This section applies “Unproven ≠ False” at that layer.
- When an obligation point returns
Unproven, the compiler must report a compilation error and must not admit the code. Diagnostics must prompt for evidence: in the refinement domain, write a proof function or reference a proof-library entry (§4.3); in the equality domain, provide a normalizable form. Changing the signature or adding a bridging axiom follows the three cross-signature paths in §4.1. UnprovenandDisprovedmust be distinguishable:Disprovedcarries a counterexample (a concrete assignment or two non-equivalent sides), whereasUnprovencarries the unsolved proposition and its reason. RenderingUnprovenas “does not hold” is an incorrect report.Unprovenmust not be degraded to an internal compiler error (E8001). E8001 denotes only an internal consistency failure of the compiler; budget exhaustion and capability boundaries are boundaries of compiler reasoning and belong to user-facing diagnostics (RFC-013 “Message Quality Specification” §5).Unprovenmust not pass silently. When a decision point ends in failure, the diagnostic the user sees may come only from an existing failure path; no second diagnostic path is added, and inability to decide never causes acceptance.
12.3 Diagnostic Shape
An Unproven diagnostic must carry all three of the following; missing any one means it is incomplete:
- Unsolved proposition: renderable proposition text (a refinement constraint, the two sides of an equality, or a termination measure);
- Reason: a capability boundary (outside the kernel’s inference rules), budget exhaustion, or an unbound symbol name—one of these;
- Location: source location. A decision point that genuinely has no location uses a default location, with the reason recorded in an implementation comment.
Budget details are presented as a one-line summary (for example, “budget 10000 steps, 10000 steps used”). The complete step count, internal solver traces, and failure shapes belong in the verbose channel or logs, not in default output.
This section is a formal relaxation of §4.1’s “Unproven → compilation error + unsolved proposition + budget-consumption report”: the substance is unchanged—users must still be able to distinguish “cannot compute this” from “does not hold”; only the granularity of the “budget-consumption report” is relaxed. The reason is that the complete step count has no action value for users (they cannot use it to modify the program), and it drifts with implementation details; after restricting it to a one-line summary, diagnostic stability and readability improve, while distinguishability is guaranteed by the “reason” field.
The “evidence-supplementation prompt” for Unproven belongs in the reason field of the diagnostic: a capability boundary explains what lies outside the current signature.rules; budget exhaustion provides a one-line summary; an unbound symbol name identifies the name for which evidence is needed. See the code-table draft section of RFC-013 for the division of labor between general Unproven and refinement-specific codes (E4023 / E2031).
13. Erasure Model: Certificates Retained at Compile Time, Erased at Runtime
Three kinds of “erasure” must be distinguished, because they act on different objects:
| Object | Compile time | Runtime | Basis |
|---|---|---|---|
Certificate (a proof term verified by Kernel::check) | Retained: Proved(checked) enters the compile-time cache for incremental reuse and checking Σ construction obligations | Completely erased: no runtime code is generated and no data slot is occupied | §4.1, §4.2 |
q=0 compile-time value parameter / Σ witness field | Exists as a quantified fact and evidence obligation (§14) | Occupies no slot; CreateStruct contains only data fields; value-level b.w is rejected (E1114) | RFC-011 §4.1, I4/I6, §14 |
| Bool check inserted by dispatch in Runtime mode | Neither a witness nor a certificate | Retained: executed at the value level | §11 |
Certificates are compile-time objects. After check succeeds, Proved(checked) lives only at compile time: it pins down “this obligation has been verified under signature.hash,” and the cache key contains signature_hash + proposition + certificate, so changing the signature invalidates it (§4.1). The runtime neither needs nor may carry the certificate—the type-level proof has been erased, and q=0 slots and Σ witnesses likewise occupy no runtime layout (quantifier-reading I4 “complete erasure” and I6 “witness erasure ≠ runtime check”).
Runtime checks are unrelated to certificates. When §11 dispatches to Runtime mode, it inserts a value-level Bool check that examines runtime values; it is not a proof term verified by the kernel. Retaining it does not violate “erasure of certificates at runtime”; the two act on different objects and are not substitutes: witness erasure, certificate erasure, and check retention.
Consistent with the unified term world: propositions, certificates, q=0 terms, and Σ witnesses are all terms from the same compile-time world; erasure follows from the single rule “compile-time terms do not enter the runtime layout,” rather than introducing a separate erasure rule for proof terms. See §14 for how Σ record fields become evidence obligations, how constructors produce certificates, and how b.w is used at the type level. §13 and the implementation gap in §8.6 are recorded in parallel: the current predicate.rs does not yet produce a Certificate, so “certificates are retained at compile time” has not yet landed.
14. Dependency Record Σ: Evidence Fields, Construction, and Type-Level Use
A Σ dependency record is a record type in the unified term world: later fields may refer to the names of earlier fields. The records in this section are a source of obligations for the §4 proof kernel—a constructor must provide, for every evidence field, a certificate verified by Kernel::check(signature, certificate, proposition); certificates are retained at compile time and erased at runtime as described in §13.
This section defines the complete semantics: position rules (§14.1), construction and layout (§14.2), generics (§14.3), cross-module export (§14.4), type-level use (§14.5), and immutability and diagnostics (§14.6). Generics, cross-module use, and type-level use are all defined here rather than deferred to later work.
14.1 Field Position Rules: The proof-space Criterion for Evidence
Suppose the fields of record declaration R, in source order, are f₀, f₁, …, fₙ₋₁, and field fᵢ has type Tᵢ. The decision has three steps: first determine space (proposition family or data family), then determine argument position (preceding / self / forward), and finally determine the field category. There is no cross-field inference and no guessing from field names:
First step (the proof-space criterion, the sole criterion). Normalize Tᵢ and take the SortDecl.space of the resulting type family (§4.1):
space = Proof(Tᵢreduces to a proposition / refinement type /Assert/Terminates/ proof-family result) ⇒ enter the evidence decision;space = Data(TᵢisInt,Array,Vec, an ordinary record, or a data type family application) ⇒ a data field, regardless of how many preceding fields it refers to.
The n in Array(Int, n) refers to a preceding data field and changes the “length of the data slot”; it does not “generate a proof.” Treating it as a witness would erase the buffer from the runtime layout—the exact misclassification this section is intended to eliminate. space is registered in signature.sorts / the library manifest, and both Kernel::check and field classification read the same registration.
Second step (position criterion). This applies only to Tᵢ = P(a₀,…,aₖ) when space = Proof, and classifies the arguments by the positions to which they refer:
- If all arguments are strictly preceding data fields
fₕ (h < i), compile-time constants, compile-time value parameters (RFC-011 §4.1 / SPEC §4.3 q=0 parameters such asMatrix’sRowsandCols), or type parameters ⇒ the third step classifies the field as evidence. A compile-time value parameter takes a concrete constant after instantiation and is counted as a compile-time constant (verbatim consistent with SPEC §8.3.1); an uninstantiated open term is left for the construction site to judge asUnproven(§14.3); - If an argument is
fᵢitself (a self-referential refinement such asv: Pos(v)) ⇒ the third step classifies it as a data field (admission): the field is the variable that carries the value, and theRefinedconstraint merely checks its own value rather than proving a fact elsewhere; - A forward reference to a later field
fₕ (h > i), a reference to another evidence field, or usingfᵢitself as an evidence argument while mixing it with other fields (SelfMixed:P(fᵢ, fₕ); pure self-referenceP(fᵢ)is the admission case in the preceding row, and the two are not conflated) ⇒ rejected at declaration. APwhose kind is data family is a different category, judged at declaration/instantiation under §14.3.
Third step (category criterion). space=Data ⇒ data field; space=Proof + preceding arguments (including compile-time value parameters / compile-time constants / type parameters) ⇒ evidence; space=Proof + self-reference ⇒ data field (admission).
| # | Form | Decision | Quantity | Runtime layout |
|---|---|---|---|---|
| 1 | space=Proof and all arguments are strictly preceding data fields / compile-time constants / compile-time value parameters / type parameters (positive example w: Pos(v)) | Evidence / witness field | Some(Quantity::Zero) | Occupies no slot, is absent from CreateStruct, and base does not enter the runtime layout |
| 2 | space=Data: ordinary value types (n: Int), data type family applications (positive example data: Array(Int, n)), ordinary records | Data field | None | Occupies a data slot and enters CreateStruct |
| 3 | space=Proof, but the argument is fᵢ itself (self-referential refinement v: Pos(v)) | Data field (admission) | None | Occupies a data slot; the Refined constraint is checked at the construction site under the existing obligations in §3.1 / §3.3 |
| 4 | space=Proof, but there is a forward reference to a later field fₕ (h > i), a reference to another evidence field, or use of fᵢ itself as an evidence argument mixed with other fields (SelfMixed; pure self-reference appears in row 3) | Illegal: rejected at declaration, with no silent degradation | — | No field is produced |
The four rows do not overlap: row 2 means that “ordinary value types / data families” are always data fields; row 3 means that a “proposition family with pure self-reference” is an admission data field; row 4 means that a “proposition family with an illegal position” is always rejected at declaration. SelfMixed falls under row 4: pure self-reference P(fᵢ) is the admission in row 3, while using the field itself as an evidence argument and mixing it with other fields in P(fᵢ, fₕ) is rejected at declaration; the two are distinguished by whether the free-name set is exactly {fᵢ}. There is no path under which “a forward reference also counts as a data field”—a forward reference neither occupies a data slot nor enters runtime_field_index.
A witness may depend only on strictly preceding data fields. The arguments of an evidence field fᵢ: P(fₕ,…) must not refer to another evidence field, must not forward-reference a later field, and must not use fᵢ itself as an evidence argument (pure self-reference is the admission in row 3 of the table, while mixed self-reference is the declaration-time SelfMixed rejection in row 4); the criterion for the kind of P is given in §14.3. This combination of “proof space + strict precedence + data fields only” ensures that, when the construction site reaches fᵢ in declaration order, all arguments already have compile-time values, the proposition is closed, and a certificate can be submitted to check.
Positive example (evidence) and counterexample (data family):
Pos: (v: Int) -> Type = { v > 0 } // space=Proof
Box: Type = { // Positive example: w is evidence
v: Int, // f0 data field
w: Pos(v), // f1 evidence: P=Pos is Proof, and argument v is a strictly preceding data field => q=0
z: Int, // f2 data field; runtime index = 1 (w is skipped)
}
Buf: Type = { // Counterexample: data is still a data field
n: Int, // f0 data field
data: Array(Int, n), // f1 data field: Array is a Data family; n only determines the length and does not generate proof
// Runtime index = 1; occupies a slot and enters CreateStruct
}
Admission: Type = { // Self-referential refinement: data field, not evidence
v: Pos(v), // Proof family, but the argument is itself => admission (row 3 of the table)
}
// Compile-time value parameters as evidence arguments (RFC-011 §4.1 / SPEC §4.3, §8.3.1)
Matrix: (T: Type, Rows: Int, Cols: Int) -> Type = {
_assert_rows: Assert(Rows > 0), // Rows is a compile-time value parameter (q=0) => evidence
data: Array(Array(T, Cols), Rows), // Array is a Data family => data field
}The Rows and Cols of Matrix are compile-time value parameters (taking concrete constants after instantiation). Assert(Rows > 0) has space=Proof and its argument is a compile-time value parameter, so _assert_rows is an evidence field; data refers to the same compile-time value parameters, but Array has space=Data, so data remains a data field. The criterion in B.2 for “compile-time value parameters” is therefore clear: whether it is referenced in type position (the strength declaration in RFC-011 §4.1), rather than guessing from the field name.
base does not enter the runtime layout: w: Pos(v) is not “an Int value”; it is “a proof of Pos(v).” Its Refined.base (Int) is merely type information for kernel equality/normalization and must never cause a runtime slot to be allocated for w. StructType.fields represents these separately with Vec<StructFieldInfo>{ name, ty, quantity, is_mut, has_default }: quantity == Some(Quantity::Zero) denotes a witness, and None denotes a data field; here, None means “data field,” not “unresolved.”
Evidence fields must not have default values (source-level clause). An evidence field has no runtime value to supply, and the construction view in §14.2 has no argument position for it, so the form field: Type = expression must not appear on an evidence field; StructFieldInfo.has_default is always false for a witness. Giving an evidence field a default value (w: Pos(v) = expr) is rejected at declaration (DefaultOnEvidence); it is neither silently treated as a data field with a default nor included in the constructor’s default-value filling. Data-field default rules (optional at construction / required when no default is present) apply only to data fields; the corresponding clauses in SPEC §3.1.1 and §8.3.1 are based on this clause.
At the representation layer, ast::StructField.quantity, mono::StructFieldInfo.quantity, and ir::TypeDeclField.quantity have the same type; mono::quantity_is_witness / StructFieldInfo::is_witness / is_witness_bearing are the sole decision functions; mono::runtime_field_index is the sole mapping point from declaration order to runtime data order (it returns None for a witness). The pre-classification space lookup reads signature.sorts / LibraryRef.manifest, not a second classification table.
14.2 Constructors: Data-Only at the Source Level, Evidence Automatically Synthesized at Compile Time
The source-level constructor has exactly one form: Box(v, z) (data arguments, in declaration order). Evidence fields occupy no constructor argument positions—there is neither a syntax for “passing a witness as a value” nor an “evidence argument position”; the arity of Box counts only the data fields v / z, not w. Evidence does not come from constructor arguments; it comes from proof obligations generated automatically at the construction site. Three views are thereby distinguished:
| View | Form | Arity | Who produces the evidence |
|---|---|---|---|
| Source-level / compile-time construction view | Box(3, 5) | compile-time arity = runtime arity = number of data fields (2 here: v, z) | The construction site automatically generates a FieldObligation; the producer delivers a candidate Certificate → Kernel::check |
Runtime construction view (translator::synthesize_constructor / CreateStruct) | Box(3, 5) | runtime arity = 2 | None: CreateStruct.operands contains only the data-field local slots v=3, z=5 (the runtime index of z is 1, skipping w), and local_count is based on the number of data fields; there is no w |
The automatic-synthesis path substitutes the compile-time values of strictly preceding data fields into P, yielding a closed proposition; the producer (§8: kernel-direct rules / Γ evidence / proof library / SMT search) delivers a candidate Certificate, and Kernel::check(signature, certificate, proposition) verifies it; Proved(checked) is retained at compile time and erased at runtime as described in §13.
Default values serve data fields only. Under the source-level clause in §14.1, evidence fields must not have defaults: the optional flag generated by bind_args_to_params comes only from the has_default field of data fields; witness fields enter neither param_names nor optional; default-value filling in translator::synthesize_constructor and missing-field slicing in ir_gen follow the non-witness field order, so no default expression or zero register is generated for an evidence field. When Box(3, 5) omits a data field, the data-field default or zero value is filled in; omitting an evidence field is not meaningful because it has no argument position to omit.
Explicit evidence is not a constructor argument; it is an independent declaration. When the automatic producer cannot deliver a verifiable certificate (Unproven), the programmer supplies explicit evidence as described in §4.3—write an independent proof function whose return type equals the proposition to be proved, or register a named proof in a proof library; these are referenced by FieldObligation as EvidenceRef::ExplicitProof / LibraryProof. The construction expression is not rewritten, no Box(..., proof) form is introduced, and no default value is given to an evidence field (§14.1 rejects DefaultOnEvidence at declaration). Passing one extra evidence argument to a source-level constructor (Box(3, 5, evidence)) is not allowed: under the six argument-binding rules, the extra argument cannot be assigned to any data-parameter slot and produces an E1010 / E1014-family argument error rather than being silently swallowed.
FieldObligation must represent both “a certificate has not yet been produced” and “a verified certificate exists.” Therefore, the original evidence: EvidenceRef (which could refer only to explicit evidence and could not hold a producer-synthesized Certificate) is split into two slots:
FieldObligation {
record : TypeId,
field : FieldId,
proposition : Proposition,
evidence_ref : Option<EvidenceRef>, // 程序员补的显式证据;自动合成时为 None
certificate_ref: Option<CertificateRef>,// producer 合成并经 check 的证书;未验证时为 None
signature_hash : ContentHash,
}
CertificateRef { id: CertId, signature_hash: ContentHash } // 指向 §13 编译期缓存里的 Proved(checked)The legal combinations are: (Some(ev), None) = explicit evidence awaiting replay; (None, Some(cr)) = automatically synthesized and verified; (None, None) = awaiting producer search; (Some, Some) is illegal (one obligation may not consume two proofs). After check succeeds, certificate_ref is written, while evidence_ref is retained as provenance.
FieldObligation is generated during the refined walk in checker/refinement.rs; field binding reuses bind_args_to_params (the six argument-binding rules), and decisions reuse the sole unit judge_refined_obligation. No value is invented when proof fails: under §4.3, explicit evidence is supplied or Unproven is returned (E2031 / general E4023); there is no such thing as an incorrectly written “witness value.”
A self-referential refinement field (v: Pos(v)) is a data field: its Refined constraint is decided at the construction site under the existing call-site obligations (§3.1 / §3.3). It is not an evidence field, does not produce a FieldObligation, and does not change runtime_field_index.
14.3 Generic Records: proof family Parameter P (kind T -> Proposition)
A type is a “parameterized record + proof family parameter,” not “a generic witness to be supplied later.” The kind of P comes from the same source as the proof-space criterion in §14.1: the result sort must be space=Proof; that is, P is a proof/type family (a proposition family), not a data family (a data type family). T -> Proposition is kind notation (Proposition is an alias for the SortSpace::Proof sort in §4.1), not a source-level type name: the yaoxiang block below uses the form P: (T: Type) -> Type accepted by the current parser, and the kind constraint is checked at declaration and instantiation rather than being written in parseable code.
Pos: (v: Int) -> Type = { v > 0 }
// Source-level form: P is a type-level function parameter; the kind constraint (result space=Proof) is explained in the prose
Cell: (T: Type, P: (T: Type) -> Type) -> Type = {
v: T, // Data field
w: P(v), // Evidence: P is a Proof family, and argument v is a strictly preceding data field
}- Kind criterion (prose notation, not source-level syntax): in
P: T -> Proposition,Propositionis an alias for theSortSpace::Proofsort (§4.1); equivalently, the application result ofPhasspace=Proof.Array: (T: Type, N: Int) -> Typehasspace=Data, so passing it toCellis a kind mismatch, rejected at declaration (the parameter declaration’s kind isT -> Proposition; binding a data family is a type error, not a case in which “wdegrades to a data field”; row 2 of §14.1 governs only fields that directly name a data type family). The multi-variable form(T, U) -> Propositionis analogous; all arguments must fall on strictly preceding data fields in declaration order. PandT: Typeboth occupy compile-time parameter positions (q=0, RFC-011 §4.1). WhenCell(Int, Pos)is instantiated,Pis bound to the concrete predicatePos(space=Proof), and the proposition ofwbecomesPos(v); the position rules are verbatim identical to §14.1.Cell(Int, Array)is rejected at declaration/instantiation because the kind does not match.Pis not a value parameter and occupies no runtime slot. WhilePremains unbound (an uninstantiated generic), the result sort ofwis stillProof(the kind has been declared), but the proposition is open and the construction site returnsUnproven(not a declaration-time rejection), without silently admitting it or degrading it to a data field. After instantiation, the decision is rerun under §14.1.- The evidence decision for a generic record is rerun under §14.1 after instantiation: after
substituteinsertsP, thequantityofStructTyperemainsSome(Zero); the Struct arms ofmono::substituteandtypes::solverpropagate the fieldquantityand do not construct a second decision. - Export of the generic
Cellcarries the kind ofP(T -> Propositionnotation) and the field-obligation template throughTypeDefPayload(§14.4); the correspondence between the source-level(T) -> Typeand kind notation is supplied by the criterion at declaration/instantiation.
14.4 Cross-Module Export: TypeDefPayload Carries Propositions/Evidence Slots
When a record containing evidence fields is used across modules, its propositions and evidence slots must be exported together with the type definition; the importing module must not “guess again from field names.” The carrier is frontend::module::TypeDefPayload:
TypeDefPayload {
// …既有字段…
type_params : [TypeParam { name, kind }] // 含 P: T -> Proposition(§14.3)
field_obligations: [FieldObligation] // 见 §14.2;无 witness 的记录为 []
evidence_slots : [EvidenceSlot {
field : FieldId,
quantity : Quantity, // 恒为 Zero
proposition : Proposition, // 可含 FieldPath 前序引用
evidence_ref : Option<EvidenceRef>, // 显式证据来源;自动合成时为 None
certificate_ref: Option<CertificateRef>, // 已验证证书引用;未验证时为 None
signature_hash : ContentHash, // 随 §4.1 签名失效
}]
libraries : [LibraryRef] // 命题/证据引用到的库,跨模块随导出携带
}- Export surface: when
checker.rsconstructsTypeDefPayload, it fills oneEvidenceSlotfor every field whosequantity == Some(Zero);field_obligationsandevidence_slotshave the same source and are not written separately. - Import surface: after receiving an
EvidenceSlot, the importer verifies it using its own currentLogicSignature—ifsignature_hashdoes not match, it follows the three cross-signature paths in §4.1 (translation term / bridging axiom / reproof) and must not directly reuse the exporter’sProved; every library referenced inlibrariesmust appear in the importer’slibrarieslist, or the result isUnprovenwith a prompt to register the library or write a bridge. - Multi-file/multi-module construction sites reuse the same
judge_refined_obligation; cross-module use does not introduce a second decision entry point (RFC-039’s prohibition on silent channels).
14.5 Type-Level b.w: ConstExpr::FieldPath + Evidence Term
A witness field may only be used at the type level (b.w is user-writable type-level syntax, as described in the note replacing 4A at the end of this section); value-level reads are always rejected:
- Term representation:
ConstExpr::FieldPath { base: Box<ConstExpr>, field: FieldId }is a field-path term in the unified term world.b.win type position resolves toFieldPath(NamedVar("b"), "w"); it denotes not a runtime value but the evidence term (proof term) corresponding toEvidenceSlot.evidence_ref. - Evidence term:
EvidenceTerm(FieldPath, EvidenceRef, signature_hash)is a source ofEvidenceReffor aCertificate(§4.2), corresponding to the explicit evidence or verified certificate in the two slotsFieldObligation.evidence_ref/certificate_ref(§14.2). Whenb.wis used in another proposition (such asQ(b.w)), the producer usesEvidenceTermas a premise of the candidate certificate, andKernel::checkreplays it under the signature; it is not reused ifsignature_hashdoes not match. - Type-level uses:
FieldPathmay appear in predicate arguments, type-constructor argument positions, as an evidence-term premise of another proposition, and inTypeDefPayload.evidence_slots[i].proposition(indexed slot by slot). Note: aFieldPaththat points to a witness is a proof-term premise, not a “data-field argument”—the rule in §14.1 that “evidence-field arguments accept only strictly preceding data fields” constrains the data arguments ofP; it does not prohibit using the proof term of a preceding evidence field as a premise of a new proposition (the latter is replayed throughEvidenceTermbycheck).b.wproduces no runtime value and occupies no data slot. - Value-level rejection: when
b.wappears in a value expression (theStructarm ofFieldAccessand theTypeRef→Structarm), report E1114 (witness_field_not_readable).FieldPathis not a value term, and neither theEvaluatornor IR generation materializes a value for it. - The exhaustive
matchoverConstExpr(const_eval::substitute,free_names,Display, thetranslate::family,proof_execution,fold_proof_call_arg, etc.) must handleFieldPath; an evaluator for an unsupported term language returnsUnprovenforFieldPathrather than silently treating it asNamedVar.
// Design sketch (non-compilable fragment: Proved / FieldPath / evidence terms are kernel terms; see the interface definitions in this section)
// Type-level use: treat b.w as an evidence premise, not as a value read
useWitness: (b: Box) -> Type = { Proved(b.w) } // b.w resolves to FieldPath + evidence term
// Value-level b.w => E1114Replacing 4A’s “no user syntax at the type level.” The premise of the 4A decision (submission information for task 6.9.5, H0 decision, 2026-11-13) was that “
b.wrequiresConstExpr::FieldPathand a proof token, belongs to an independent term-language design, and adding it now would create a second term world,” and it therefore decided that V1 would not provide user-facingb.wprojection.ConstExpr::FieldPath,EvidenceTerm, andTypeDefPayload.evidence_slotsall belong to the same unified term world (§4, not a second term world), so that premise does not hold: type-levelb.wis user-available syntax (theuseWitnessexample above). The 4A clause “no user syntax for type-levelb.w” is therefore replaced by this section and is no longer in effect. The other two 4A clauses—witnesses are compile-time fields, proved at construction, and erased at runtime; the field representation usesquantity+ proposition type—remain in effect. Value-levelb.wis still rejected under 4A (E1114).FieldPathexists only in type/proposition positions; it is not a runtime field path and does not constitute an “A-style runtime field.”
14.6 Immutability, Erasure, and Diagnostic Codes
- 5A is wholly immutable: a record containing any evidence field is wholly immutable—data fields must not declare
mut, undergo field assignment, be borrowed through&mut, or serve as the receiver of a write method (including automaticWriteBorrow). Otherwise, a witness proposition could become invalid due to a field rewrite, and there is currently no runtime check / revalidation; violations report E1115 (witness_record_immutable). A finer-grained linearity/uniqueness design is deferred to a separate RFC. - Erasure: an evidence field has
quantity=Zero⇒ it occupies no runtime slot;CreateStruct/GetField/SetField/resolve_field_indexrecognize only the data order ofruntime_field_index; aProved(checked)certificate is retained at compile time and erased at runtime as described in §13; Runtime-mode Bool checks are unrelated to witnesses. - Diagnostic-code division of labor (each code handles one aspect, without borrowing another code or failing silently):
| Code | Trigger | Semantics |
|---|---|---|
| E4018 | An evidence proposition at a construction site is judged false (a counterexample confirmed through check / a kernel-direct decision) | Refinement-predicate violation, with counterexample |
| E2031 | An evidence proposition at a construction site is Unproven (refinement path, with the assigned/var/constraint slots) | Refinement constraint cannot be proved; prompts for explicit evidence (§4.3) |
| E1114 | Value-level read of witness field b.w | A witness field cannot be read at the value level |
| E1115 | mut / field assignment / &mut / write receiver on a witness-bearing record | The record is wholly immutable |
| E4023 | General Unproven outside the refinement path (such as an unsupported FieldPath evaluator) | General inability to prove, with proposition/reason/location (§12.3) |
ProofFunctionRequired still uses E4020; the division of labor between general Unproven and E2031 remains unchanged (§12.3, RFC-013). The declaration-time rejection list (aligned item by item with row 4 of §14.1 and the kind criterion in §14.3) contains four categories:
| # | Rejected form | Description |
|---|---|---|
| 1 | space=Proof with a forward reference to a later field fₕ (h > i) | Illegal position |
| 2 | Reference to another evidence field as an argument | Illegal position |
| 3 | Use of fᵢ itself as an evidence argument mixed with other fields (SelfMixed: P(fᵢ, fₕ)) | Illegal position; pure self-reference P(fᵢ) is the admission data field in row 3 of §14.1 and is not rejected |
| 4 | The kind of P is data family (§14.3) | Kind mismatch; a type error at declaration/instantiation |
In addition, giving an evidence field a default value (w: Pos(v) = expr, DefaultOnEvidence, the source-level clause in §14.1 / construction clause in §14.2) is also rejected at declaration—it has no runtime value to supply and is not silently treated as a data field. Rows (1)–(3) above are the illegal-position forms in row 4 of §14.1 (item 3 is SelfMixed), while item (4) is the kind mismatch in §14.3; together they constitute the four declaration-time rejection categories. Default values are an independent field-declaration check and are not merged into the four categories.
All of these are rejected directly at declaration; they do not reach the construction site and are not silently degraded to data fields. A space=Data data type family application (including Array(Int, n)) and a space=Proof pure self-referential refinement (v: Pos(v), admission) are both legal data fields. An uninstantiated generic is not a declaration-time rejection: under §14.3, while P is unbound, the result sort of w remains Proof and the proposition is open, so the construction site returns Unproven (E2031 / E4023), without silently admitting it or degrading it to a data field. Assignment of declaration-time diagnostic codes (adding new declaration-time codes or reusing E1001/E1114/E1092) is deferred to the implementation-round D2 decision; this section defines only the rejection list and semantics and does not reserve code numbers.
Detailed Design
Syntax Changes
| Before (RFC-022) | After (This RFC) |
|---|---|
//! requires: NonEmpty(n) = n > 0 | Compile-time predicate as the parameter type (b: Positive(b)) |
//! ensures: ExistsMax(result, arr) | Return type uses a return-value formal parameter -> (result: IsMax(T, arr, result)) |
/*! invariant: ... !*/ | Compile-time predicate type annotation on the variable—a Floyd–Hoare invariant |
//! decreases: n | Measure is written in the refinement-type position (Terminates); the compiler explores automatically first and requires an explicit measure only if exploration fails |
| Specifications are comments | Specifications are part of the type system |
/*! invariant: ... !*/ with no other record evidence | Dependency record Σ: distinguishes evidence fields (q=0) from data-family fields using the proof-space criterion; see §14 |
Syntax
Compile-time predicates introduce no new keywords. {} is the proof space and is exactly consistent with the existing type-definition syntax. A compile-time predicate is simply a function that returns Type—name: (params) -> Type = { assertions }. When used, it is a function call—Positive(b), IsMax(T, arr, result).
# 编译期谓词 = 返回 Type 的函数,{} 内为编译器验证的断言
# 使用现有函数/类型语法,无需新增 BNF 规则
predicate ::= identifier ':' params '->' 'Type' '=' '{' assertions '}'The arguments of a predicate application must have compile-time constant forms—literals, variables (bound by name), type applications (recursively extracted), or compile-time referable function references (function names). An argument shape that cannot be converted to a constant expression reports E1092; a mismatch between the number of arguments and the predicate declaration’s parameter count reports E1093. Arguments are bound positionally to the parameter list, and predicate arity is determined by the declaration—Positive(x) is unary, IsMax(T, arr, result) is ternary, and Terminates(m) and Terminates(FnType, m) are unary and binary—refinement constraints are never silently discarded (previously, an argument that could not be converted caused the constraint to disappear silently, allowing invalid bindings to pass silently).
New syntactic concept: the return-value formal parameter—in -> (name: Type), name is a return-value formal parameter.
The return-value formal parameter is one of the syntactic concepts that YaoXiang introduces over its existing function syntax (record evidence fields reuse existing field syntax; see §14). Its semantics are:
- The value of
nameis supplied by areturnstatement nameexists only in the type signature and is referenced by postcondition predicates (such as-> (result: IsMax(T, arr, result)))namedoes not enter the function-body scope and does not appear at call sites- The return-value formal parameter is optional—when there is no postcondition, the signature is identical to that of an ordinary function (
-> Int), with no additional burden
The reason for introducing it is that a postcondition needs to refer to “the value the function is about to return.” Without a return-value formal parameter, the compiler could only use special rules (such as the implicit variable $result or __retval__) to let a predicate refer to the return value. A return-value formal parameter makes this reference explicit—it is just a formal parameter, except that its value is supplied by return rather than by the caller.
Proof functions are not a new concept—they are simply YaoXiang functions whose return type is the proposition being asserted. When the compiler returns Unproven, the programmer supplies a proof function, and the type checker verifies it in exactly the same way that it verifies the return type of any function. No new syntax, keywords, or rules are needed.
The boundary between the two. In the correctness domain (predicate Unproven), proof is supplied in the body: write a function whose return type is the proposition to be proved. In the termination domain (§6.9), the measure is supplied in type position: write
Terminates(measure)as the type of a binding or function signature. The former is “write a proof for a proposition that cannot be proved,” while the latter is “explicitly declare a measure that cannot be discovered by exploration”—the mechanism is the same in both cases (a refinement-type application), but the placement differs. The termination domain does not require writing a_prooffunction.
Type-System Implications
- Type universe: compile-time predicates occupy the Type₂ layer—they accept functions that return values of type Type, at the same level as type constructors
- Generic interaction: compile-time predicates may carry generic parameters, such as
NonEmpty: (T: Type) -> (arr: Array(T)) -> Type - Ownership interaction: expressions in compile-time predicates obey ownership rules and may only be read, not written
- Type inference: parameters of compile-time predicates participate in HM type inference
- Dependency record Σ: record fields are divided into data fields and evidence fields (
Quantity::Zero) according to the proof-space and position rules in §14; the proof-family parameterP: T -> PropositionandTypeDefPayload.evidence_slotsprovide complete semantics for generics and cross-module use
Runtime Representation
Compile-time predicates are handled at runtime according to the dispatch result:
- CompileTime mode (all free variables are known at compile time): after
Kernel::checkverifies the certificate,Proved(checked)is retained at compile time and completely erased at runtime.Positive: (x: Int) -> Type = { x > 0 }—the runtime representation of a parameterb: Positive(5)is simplyInt; the refinement condition{ 5 > 0 }has passed, and the certificate does not enter the runtime layout. Σ evidence fields behave the same way under §14:basedoes not enter the layout,CreateStructis data-only, and value-levelb.wreports E1114. - Runtime mode (some free variables are runtime values): retain the runtime check—execute a Bool check at the value level and inject the flow-sensitive assumption set Γ. See the dispatch routing pipeline in §11 and the erasure model in §13.
Placing a compile-time predicate in type position (such as f(x: Positive(x))) does not create a wrapper type or allocate extra memory. However, if x comes from runtime input, a runtime Bool check is inserted.
Interaction constraint with ref: compile-time predicates may refer only to immutable borrows or values whose ownership has already been transferred. A compile-time predicate that refers to a mutable borrow cannot guarantee at compile time that the verification result remains valid at runtime—such use is a direct compilation error.
Compiler Changes
- Parser: compile-time predicates and proof functions use standard function syntax and require no additional parsing rules
- Proof kernel:
Kernel::check(signature, certificate, proposition)andCheckVerdict; replayCertificate.stepsaccording tosignature.rules; the sole exit toProved - Logic signatures and libraries:
LogicSignature(sorts / rules / axioms /libraries: [LibraryRef]/ hash); everyLibraryRefcarrieskind/id/manifest/hash; the signature hash covers all libraries; signatures are replaceable, and cross-signature use follows explicit translation or a bridging axiom - Certificate producers (untrusted): kernel-direct rules, Γ/
q=0evidence, proof functions, SMT-LIB 2.6 translation (default Z3, alternative CVC5), tactics, and proof search; all deliver only candidateCertificates, andunsatnever reachesProveddirectly (§8) - Verification-condition generation: WP/SP calculi, loop invariants, and
FieldObligations for record construction under §14 (field position rules /bind_args_to_params/judge_refined_obligation) produce propositions and candidate certificates without deciding them directly - Error reporting: counterexamples (confirmed by
check) + unsolved proposition + reason + evidence-supplementation prompt + source-location association (§12.3)
Backward Compatibility
- ✅ Code that does not use compile-time predicates remains completely unchanged
- ✅ Compile-time predicates have zero runtime overhead in CompileTime mode; Runtime mode retains only the necessary Bool checks
- ⚠️ RFC-022’s
//!syntax is no longer supported—but 022 was never implemented, so there is no migration burden - ⚠️ Record types gain the evidence-field position rules in §14: programs in which “a field name happens to be a predicate application, silently treated as a data field” now receive compile-time witness decisions (value-level reads report E1114; witness-bearing records are immutable and report E1115). This is an externally visible behavior change and is registered as a semantic-correction D/E-class change
Trade-offs
Advantages
- Complete fulfillment of the Curry–Howard correspondence: types are propositions, programs are proofs,
name: Proposition = Proof; propositions and certificates inhabit the unified term world - Uniformity: compile-time predicates and ordinary functions use exactly the same syntax, with no conceptual split
- Transparent producer: programmers need not know that SMT exists; the mental model is “supply explicit evidence → the kernel verifies it under the signature”; backends are replaceable
- Incremental adoption: begin with one compile-time predicate and gradually expand coverage
- Minimal runtime overhead: certificates and
q=0terms are retained at compile time and erased at runtime; Runtime mode retains only the necessary Bool checks
Disadvantages
- Compile time: producer search and kernel replay both increase compile time, but the producer budget (§8.4) and certificate step limit keep this under control
- Limits of automatic proof: when a producer cannot deliver a verifiable certificate, the kernel returns
Unprovenand prompts for evidence. This is not a language deficiency—it is an inevitable consequence of the halting problem. The kernel honestly distinguishes “cannot compute this” from “does not hold” - Learning curve: writing effective compile-time predicates and proof functions and choosing logic signatures requires understanding the Curry–Howard correspondence and the basic intuition of being “signature-relative”
- Implementation complexity: unifying the compile-time proof pipeline requires careful design
Risk Mitigation
- Hard producer budget limits (10,000 search steps / 100ms / instantiation depth 3) and a certificate replay-step limit; exceeding the budget returns
Unproven(§8.4) - Dependent-type pre-reduction: deterministic value computation is handled first by kernel-direct rules, leaving only nondeterministic work for producers
Unprovenis not a dead end: supply explicit evidence (a proof function, a proof-library entry, or a changed signature / bridging axiom; §4.3); in the termination domain, supply a measure in type position (§6.9)—all are verified byKernel::check- Incremental verification:
Proved(checked)is cached bysignature_hash + proposition + certificate, and only modules whose signature changed or whose certificate became invalid are recomputed - Clear error messages + counterexamples confirmed by
check+ unsolved proposition + reason + evidence-supplementation prompt + a one-line budget summary (§12.3)
Alternatives
| Alternative | Why It Was Not Chosen |
|---|---|
RFC-022: comment-based //! specifications | Splits specifications from types, violating the Curry–Howard correspondence |
| Separate specification files (such as CVL) | Separates specifications from code and increases maintenance cost |
| Runtime assertions only | Cannot statically guarantee correctness |
| External proof assistants (such as Coq) | Disconnect the proof from the compiler and require an independent proof language and trust boundary. YaoXiang’s choice is that proof is YaoXiang code and certificates are verified by Kernel::check under a replaceable signature, with no hard-coded trust root |
| This proposal: compile-time predicates as first-class citizens | ✅ |
Implementation Strategy
Phase Breakdown
| Phase | Contents |
|---|---|
| Phase 1 | Kernel::check + LogicSignature + Certificate + CheckVerdict; kernel-direct rules (structural equivalence, βδι-reduction, defeq) |
| Phase 2 | Manifests and hashes for axiom libraries / proof libraries; integration of proof functions and explicit evidence; a proof-producing adapter that expands unsat into ProofSteps for registered rules |
| Phase 3 | Loop-invariant VC generation + termination checking (§6, §6.9) + dependency record Σ field position rules, construction obligations, and type-level FieldPath use (§14), all using the same check |
| Phase 4 | Certificate caching by signature_hash + incremental verification + cross-module evidence slots in TypeDefPayload + cross-signature translation/bridging axioms + IDE support (§14.4) |
Dependencies
- RFC-010: Unified Type Syntax—compile-time predicates are based on
name: type = value - RFC-011: Generic System—compile-time predicates may carry generic parameters
- RFC-009: Ownership Model—expressions in compile-time predicates obey ownership rules
Open Questions
[x] Availability of Z3 for the wasm32 target: Z3 is unavailable under wasm (all SMT code is excluded by
cfg(not(target_arch = "wasm32"))). Scope and degradation direction: -ownership.rssmt_cutalways returnsfalse→ back edge is traversed → conservative rejection (sound direction, merely less narrowing) - Termination-check Strategy 1 and predicate levels 2b/3 are skipped entirelyCorrection (2026-10-01): the original text claimed that these paths were “currently unreachable” (on the grounds that
predicate_defswas never populated in production,parserdid not produceMonoType::Refined, andwith_solverin production never called it), which is no longer true—all three have landed (predicate-definition registration #377-3; refinement-type normalization; production-pipeline solver injection). Consequently, the wasm/native difference is no longer limited tosmt_cutprecision:Path native wasm Degradation direction Explicit termination-measure decision Decided UnjudgedDoes not report E4022 (fewer reports) Well-foundedness decision Decided UnjudgedDoes not report E4022 (fewer reports) SMT implication level of refinement predicates Executed Skipped Falls back to UnprovenAll are conservative directions (fewer producer search paths ⇒ fewer candidate certificates ⇒
Unproven;Kernel::checkitself is unchanged) and do not affect soundness. Under the terminology of §8.7, the table below is interpreted as “producer availability,” not “decision precision.” To achieve equal precision, see issue #376 (conclusion: prefer a JS-side Z3 instance rather than linking Z3 into the main wasm build— this would require replacing the emcc build system and increase artifacts from 3 MB to ~20 MB).[x] SMT solver selection: Z3 by default (MIT license, the broadest verification support). CVC5 is an SMT-LIB-compatible alternative selected through a compiler flag. SMT-LIB 2.6 is the producer’s translation target—it is an input format for candidate certificates, not a trust boundary; the sole exit to
ProvedremainsKernel::check(§8). No custom general-purpose solver interface is implemented, andunsatis not treated as a verdict.[x] Specific solver-budget values: producer search steps 10,000 / time 100ms / quantifier instantiation depth 3, plus a certificate replay-step limit (§8.4). Fixed inside the compiler, with no knob. If actual use cases demonstrate that these are insufficient (and not “the user wrote it incorrectly”), they may be adjusted later.
[x] Scope of quantifier support: the language layer does not restrict quantifier order. Compile-time predicates accept Type parameters—Type includes function types—so higher-order quantifiers are a natural consequence of the type system and require no special syntax. Producers can handle first-order quantifiers (forall/exists, including alternating nesting, limited by budget depth 3) and deliver candidate certificates; when a higher-order quantifier cannot yield a verifiable certificate, the kernel returns
Unprovenand prompts for explicit evidence—write a YaoXiang proof function whose return type equals the proposition (§4.3), and haveKernel::checkverify it under the current signature. No external export, no AI, and no interactive proof mode are needed. Everything is YaoXiang code, and everything is verified by the proof kernel.[x] Counterexample formatting: source variable names are used directly as SMT variable names (with a module prefix to avoid collisions). The
sat + modelreturned by a producer is a candidate counterexample and must be confirmed byKernel::checkbefore the proposition is rendered as false. Output format: variable name = concrete value + source location + predicate-definition location. No complex mapping layer is implemented.[x]
Interaction between compile-time predicates and the→ Decision: compile-time predicates may refer only to immutable borrows or values whose ownership has already been transferred. Values under a mutable borrow cannot appear in compile-time predicates.refsmart pointer?[x] Extending the
forall-predicate violation-count measure to non-adjacent operations? → No extension. The current coverage (adjacent swaps, adjacent movements) is complemented by Strategy 1 (linear rank function)—quick sort’s outer interval contraction is covered by Strategy 1, while heap sort is covered by Strategy 1 (array-index pattern). A loop that no strategy can prove terminating is rejected directly by the compiler—this is the hard-safety philosophy, not a defect. If a real-world (rather than academic-construction) scenario arises in which none of the four strategies can cover an algorithm, the issue will be reconsidered. → Reconsideration triggered (2026-09-14, #318): non-structural recursion (gcd-like non-direct decrease, mutual recursion, merge partitioning) is exactly the kind of real-world scenario this clause anticipated—the template sequence of measure exploration cannot handle it, and it cannot be rewritten into an analyzable iteration pattern without seriously harming readability. Conclusion: the hard-safety philosophy remains unchanged (an incorrect measure is still rejected by a counterexample confirmed throughcheck; humans may fail to prove something but cannot prove it incorrectly), but “failure to explore ⇒ rejection” is relaxed to “failure to explore may be handled by the programmer explicitly supplying a measure in type position”—see §6.9.[x] Combinatorial explosion in linear-rank-function enumeration: the candidate-enumeration limit is three bounded variables. At ≤3, enumerate all linear combinations and deliver a candidate certificate for each to
Kernel::check. At >3, try only single-variable measures (v_i,u_i - v_i), and report a compilation error if they fail—prompting the programmer: “this loop has more than three bounded variables; the automatic producer cannot synthesize a multivariable measure, so please supply explicit evidence.” This is not an engineering compromise—it forces programmers to write simpler loops.
References
- RFC-010: Unified Type Syntax
- RFC-011: Generic System Design
- RFC-009: Ownership Model
- Howard, W. A. (1969). The Formulae-as-Types Notion of Construction.
- Swamy, N. et al. (2016). Dependent Types and Multi-Monadic Effects in F*. POPL 2016.
- Vazou, N. et al. (2014). Refinement Types for Haskell. ICFP 2014.
- Leino, K. R. M. (2010). Dafny: An Automatic Program Verifier for Functional Correctness. LPAR 2010.
- De Moura, L. & Bjørner, N. (2008). Z3: An Efficient SMT Solver. TACAS 2008.
Lifecycle and Destination
┌─────────────┐
│ 草案 │ ← 作者创建
└──────┬──────┘
│
▼
┌─────────────┐
│ 审核中 │ ← 当前状态:社区讨论
└──────┬──────┘
│
├──────────────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ 已接受 │ │ 已拒绝 │
└──────┬──────┘ └──────┬──────┘
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ accepted/ │ │ rejected/ │
│ (正式设计) │ │ (保留原位) │
└─────────────┘ └─────────────┘