RFC-030: The assert Assertion Mechanism
Summary
Introduce the assert assertion mechanism into YaoXiang for testing, precondition checks, and runtime panics. assert and the compile-time refinement type Assert(C) (see RFC-011 §4.3) are two sides of the same refinement primitive—dispatch automatically routes them to either a compile-time proof or a runtime check, depending on whether the predicate's free variables are available at compile time. assert(false, "msg") is equivalent to raise; no dedicated throw/raise keyword is required.
Motivation
Why is this feature needed?
YaoXiang's current E2E tests can only simulate assertions through if + io.println + return:
val = some_func()
if val != 42 {
io.println("FAIL: expected 42")
return
}This approach has three problems:
- Excessive boilerplate: Each assertion requires 4 lines, bloating test files
- Weak error messages: Strings must be concatenated manually, with no source location
- Non-composability: Assertions cannot be registered in bulk or passed as arguments to test frameworks
Current Problems
- There is no unified assertion mechanism
- Test code is filled with the
if+ print +returnpattern - The bytecode layer has no
Throwinstruction (the carrier for Option A was not adopted and was removed on 2026-12-04), and the language layer exposes neither throw nor raise - RFC-011 defines the compile-time
Assert(C)conditional type, but runtimeassert()has not yet been implemented
Design Principles
assert is YaoXiang's only user-space panic mechanism. assert(false, "msg") is equivalent to raise and does not require a separate throw/raise keyword. The assert function itself is the best encapsulation of if raise.
No new keywords and no new syntax. Everything is a function call.
Option A: Native Function
Implement assert as a native function without introducing any new keywords.
use std.assert.assert
main: () -> Void = {
assert(1 + 1 == 2, "math is broken")
assert(get_name() == "YaoXiang", "name mismatch")
}Overload Signatures
assert has two overloads:
// Core signature: assert is the value-universe introduction for Assert
assert: (cond: Bool, ?msg: String | Error) -> Assert(IsTrue(cond))
// ^^^^^^^^^^^^^^^^^^^^^^^^
// Returns a refinement type, not ()
//
// IsTrue: Bool -> Type bridges truth values to types:
// IsTrue(true) = Void (⊤, execution continues)
// IsTrue(false) = Never (⊥, divergence/compile error)The actual behavior of assert is determined by dispatch:
- All free variables are known at compile time → CompileTime: The compiler evaluates
cond; true → erased to Void, false → compile error (Never is uninhabited) - Runtime free variables exist → Runtime: A check is inserted, and a refinement fact is injected into the flow-sensitive assumption set Γ
The optional message ?msg and the Result overload (see below) are retained as the runtime raise payload.
Overload 1: Conditional Assertion (Bool, ?String | Error)
Bool plus an optional message. The message may be a String or an Error value:
assert(1 + 1 == 2) // No message; default panic message
assert(1 + 1 == 2, "math is broken") // String message
assert(x > 0, my_error) // Throw an Error value directlyassert(false, "msg") is YaoXiang's equivalent of raise/throw; no separate keyword is required.
Overload 2: Result Assertion (Result)
A single Result argument, automatically checking whether it is Err:
Advantages
- No syntax changes: A pure function with no new keywords
- No new concepts: Reuses the existing native function registration mechanism
- Highly extensible: Function overloads naturally support multiple signatures
- Self-documenting: The
std.assertnamespace is itself documentation
Disadvantages
- None. When
assert's type signature is correct, the compiler can infer dead code through function reachability analysis. No additional pass is required.
Runtime Behavior
- Evaluate the first argument,
condition: Bool - If it is
true, returnUnit - If it is
false, trigger a runtime panic:- Output the
messagecontent, if present - Output the call stack in debug mode
- Terminate the current execution
- Output the
Failure Behavior of Each Overload
| Signature | Behavior on Failure |
|---|---|
assert(false) | Default panic message |
assert(false, "msg") | Print the string message, then panic |
assert(false, error_val) | Throw the Error value |
assert(Err(x)) | Extract the Err payload and panic |
Relationship with Compile-Time Assert
assert and Assert are two sides of the same refinement primitive—the dispatch routing pipeline automatically selects between them based on whether the predicate's free variables are available at compile time:
| Condition | Dispatch | Behavior |
|---|---|---|
| All free variables known at compile time | CompileTime → proof pipeline | Proved → erase, Disproved → compile error, Unknown → proof required |
| Runtime free variables exist | Runtime → insert check | Bool check + inject a refinement fact into the flow-sensitive assumption set Γ |
use std.assert
# Known at compile time (generic parameter) — takes the CompileTime path, zero runtime overhead
Array: (T: Type, N: Int) -> Type = {
data: Array(T, N),
length: assert.Assert(N > 0), # N is a generic parameter, evaluated at compile time
}
# Runtime value — takes the Runtime path, inserts a Bool check
x = read_int()
assert.assert(x > 0, "expected positive") # runtime check2026-07-12 Unified Approach: The earlier “fully independent” conclusion has been superseded.
assert()is a value-level introduction forAssert, and dispatch handles it automatically.
Compiler Changes
No changes are needed to the parser, AST, typecheck, or IR gen.
Only native function registration needs to be added under src/std/:
- Add
src/std/assert.rs - Register
std.assert.assertandstd.assert.Assert(the latter is a compile-time conditional type) - Internally invoke the existing
BytecodeInstr::Throwinstruction
Advantages
- No syntax changes: A pure function with no new keywords
- No new concepts: Reuses the existing native function registration mechanism
- Highly extensible: Function signatures can be extended to variants such as
assert_eqin the future - Self-documenting: The
std.assertnamespace is itself documentation
Disadvantages
Cannot be determined at compile time: Unlike Option B (the keyword approach), dead code cannot be eliminated at compile time→ No longer holds under the unified approach. In CompileTime mode,assertfollows the proof pipeline; a compile-time-knowncond→ erased or compile error (assert(false)→ Never → dead code).- The call stack is available only in debug mode
Option B: Built-in Keyword (Superseded by the Unified Approach)
Deprecated. The opposition between Options A and B is eliminated by the dispatch routing pipeline—
assertis the value-level introduction forAssert; compile-time-known values take the proof pipeline with zero runtime overhead, while runtime values take the check path. There is no need to choose between “function” and “keyword.” The following is a historical record.
assert(1 + 1 == 2, "math is broken")Type Signature
There is no independent type signature—the keyword is handled by the parser.
Runtime Behavior
Same as Option A.
Compiler Changes
Changes are needed to the parser, AST, typecheck, and IR gen:
- Parser: Add the
Expr::Assertvariant - AST: Add the
Expr::Assertnode - Typecheck: Validate parameter types
- IR gen: Generate
BytecodeInstr::Throw
Advantages
- The source location is known at compile time and does not depend on debug info
- Compile-time constant folding:
assert(true)→ no-op,assert(false)→ compile error
Disadvantages
| Drawback | Impact |
|---|---|
| Requires parser changes | Introduces a new syntax node and increases maintenance costs |
| Keywords are not extensible | Variants such as assert_eq still need to be functions |
| The compile-time advantage is impractical | See the analysis below |
Comparison
| Dimension | Option A (Function) | Option B (Keyword) |
|---|---|---|
| Implementation Cost | ~20 lines | parser + AST + typecheck + IR gen |
| Syntax Change | None | New keyword |
| Extensibility | Function overloads | Requires companion macros |
| Source Location | debug info | Available at compile time |
| Constant Folding | Requires pass support | Available at compile time |
| Runtime Overhead | Function call | Minimal |
Practical Constraints of Compile-Time Analysis
Option B's core advantage—compile-time analysis—requires a constant-folding pass to take effect. In other words, the compiler must evaluate the false in assert(false) at compile time to know that it is dead code.
YaoXiang currently has no constant-folding pass. Even with Option B, common forms such as assert(x > 0) still cannot be analyzed at compile time. Only literals such as assert(true) / assert(false) can be analyzed.
Therefore, Option B's compile-time advantage is theoretical rather than practical at the current stage.
Open Questions
- [x]
Choose Option A or Option B?→ Unified approach:assertis the value-level introduction forAssert. The opposition between Options A and B is eliminated by the dispatch routing pipeline—compile-time-known values take the proof pipeline, while runtime values take the check path. There is no need to “choose one.” - [x]
Should→ Supported.assertsupport the simplified formassert(cond)without amessage?assert(cond, ?msg), with an optional message. - [x]
Are variants such as→ No. YAGNI. Revisit when the test framework is ready.assert_eqandassert_neneeded? - [x]
Should panic output include the source location?→ Option A relies on debug info (the call stack). - [x]
Unifying→ Decided. Unified approach:assert/Assertassert: (Bool) -> Assert(IsTrue(cond)), two sides of the same mechanism with automatic dispatch. TheNevertype (⊥) is built in as the return type ofassert(false).
2026-07-05: Choose Option A (Superseded by the Unified Approach)
Option A's 20-line implementation offered the better balance of value and cost. After the unified approach was established on 2026-07-12, the opposition between A and B was eliminated by the dispatch routing pipeline—assert is the value-level introduction for Assert, and there is no longer a choice between “function” and “keyword.”
2026-07-12: Unified Approach Established (Supersedes the 2026-07-11 “Fully Independent” Conclusion)
Conclusion: assert and Assert are not two independent mechanisms. assert: (Bool) -> Assert(IsTrue(cond)) is dispatched automatically:
- Compile-time known → enters the proof pipeline (Proved erased / Disproved error / Unknown requires proof)
- Runtime input → inserts a check + injects a Γ assumption
Module Structure: std.assert jointly hosts the runtime assertion (assert) and the compile-time refinement types (Assert, IsTrue). They are no longer “implemented separately”; instead, they are two sides of the same primitive.
2026-07-11: assert Overload Design
Question: Why does assert need two overloads instead of a unified (Bool, ?String)?
Answer:
Runtime assert() is YaoXiang's only user-space panic mechanism. assert(false, "msg") is equivalent to raise/throw in other languages. It therefore needs to cover three scenarios:
- Condition + simple message:
assert(cond, "msg") - Condition + custom Error:
assert(cond, my_error) - Result check:
assert(result)— the simplestif is_err { panic }
The rationale for the Result overload is that it provides the shortest path for error propagation—“a Result should be Ok, otherwise die.” There is no need to call .is_ok() first and then handle the error separately.
Appendix B: Design Decision Log
| Decision | Resolution | Date | Author |
|---|---|---|---|
| Choose Option A or Option B | Unified approach: The dispatch routing pipeline eliminates the A/B opposition; assert is the value-level introduction for Assert | 2026-07-12 | Chenxu |
| Is the message optional? | Yes: assert(cond, ?msg), with a String or Error | 2026-07-11 | Chenxu |
Are variants such as assert_eq needed? | No. YAGNI; revisit when the test framework is ready | 2026-07-11 | Chenxu |
Is a separate raise/throw keyword needed? | No. assert(false, msg) is equivalent to raise | 2026-07-11 | Chenxu |
Relationship between assert and Assert | Two sides of the same mechanism. assert: (Bool) -> Assert(IsTrue(cond)), dispatched automatically | 2026-07-12 | Chenxu |
Option A's Throw bytecode carrier | Not retained: Runtime assert uses native E6005 (diagnostics include the source location and call stack); bytecode THROW with no producers was removed on 2026-12-04, and 0xA0-0xAF is left unused | 2026-12-04 | Chenxu |
References
- RFC-007: Unified Function Definition Syntax —
name: type = valuemodel - RFC-010: Unified Type Syntax — Type system foundations
- RFC-011: Generic System Design §4.3 — Compile-time verification and the
Assert(C)conditional type - RFC-026: FFI Core Mechanism — Native function registration mechanism
- RFC-027: Compile-Time Predicates and Unified Static Verification — Compile-time evaluation system
