Skip to content

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:

yaoxiang
val = some_func()
if val != 42 {
    io.println("FAIL: expected 42")
    return
}

This approach has three problems:

  1. Excessive boilerplate: Each assertion requires 4 lines, bloating test files
  2. Weak error messages: Strings must be concatenated manually, with no source location
  3. 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 + return pattern
  • The bytecode layer has no Throw instruction (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 runtime assert() 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.

yaoxiang
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:

yaoxiang
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 directly

assert(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.assert namespace 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 ​

  1. Evaluate the first argument, condition: Bool
  2. If it is true, return Unit
  3. If it is false, trigger a runtime panic:
    • Output the message content, if present
    • Output the call stack in debug mode
    • Terminate the current execution

Failure Behavior of Each Overload ​

SignatureBehavior 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:

ConditionDispatchBehavior
All free variables known at compile timeCompileTime → proof pipelineProved → erase, Disproved → compile error, Unknown → proof required
Runtime free variables existRuntime → insert checkBool check + inject a refinement fact into the flow-sensitive assumption set Γ
yaoxiang
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 check

2026-07-12 Unified Approach: The earlier “fully independent” conclusion has been superseded. assert() is a value-level introduction for Assert, 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/:

  1. Add src/std/assert.rs
  2. Register std.assert.assert and std.assert.Assert (the latter is a compile-time conditional type)
  3. Internally invoke the existing BytecodeInstr::Throw instruction

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_eq in the future
  • Self-documenting: The std.assert namespace 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, assert follows the proof pipeline; a compile-time-known cond → 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—assert is the value-level introduction for Assert; 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.

yaoxiang
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:

  1. Parser: Add the Expr::Assert variant
  2. AST: Add the Expr::Assert node
  3. Typecheck: Validate parameter types
  4. 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 ​

DrawbackImpact
Requires parser changesIntroduces a new syntax node and increases maintenance costs
Keywords are not extensibleVariants such as assert_eq still need to be functions
The compile-time advantage is impracticalSee the analysis below

Comparison ​

DimensionOption A (Function)Option B (Keyword)
Implementation Cost~20 linesparser + AST + typecheck + IR gen
Syntax ChangeNoneNew keyword
ExtensibilityFunction overloadsRequires companion macros
Source Locationdebug infoAvailable at compile time
Constant FoldingRequires pass supportAvailable at compile time
Runtime OverheadFunction callMinimal

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: assert is the value-level introduction for Assert. 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 assert support the simplified form assert(cond) without a message? → Supported. assert(cond, ?msg), with an optional message.
  • [x] Are variants such as assert_eq and assert_ne needed? → No. YAGNI. Revisit when the test framework is ready.
  • [x] Should panic output include the source location? → Option A relies on debug info (the call stack).
  • [x] Unifying assert / Assert → Decided. Unified approach: assert: (Bool) -> Assert(IsTrue(cond)), two sides of the same mechanism with automatic dispatch. The Never type (⊥) is built in as the return type of assert(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:

  1. Condition + simple message: assert(cond, "msg")
  2. Condition + custom Error: assert(cond, my_error)
  3. Result check: assert(result) — the simplest if 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 ​

DecisionResolutionDateAuthor
Choose Option A or Option BUnified approach: The dispatch routing pipeline eliminates the A/B opposition; assert is the value-level introduction for Assert2026-07-12Chenxu
Is the message optional?Yes: assert(cond, ?msg), with a String or Error2026-07-11Chenxu
Are variants such as assert_eq needed?No. YAGNI; revisit when the test framework is ready2026-07-11Chenxu
Is a separate raise/throw keyword needed?No. assert(false, msg) is equivalent to raise2026-07-11Chenxu
Relationship between assert and AssertTwo sides of the same mechanism. assert: (Bool) -> Assert(IsTrue(cond)), dispatched automatically2026-07-12Chenxu
Option A's Throw bytecode carrierNot 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 unused2026-12-04Chenxu

References ​