v0.29.0—Sharper bug analysis, reliable resource cleanup, and stronger test and CI checks.See what's new

Documentation

Refinement Types

Refinement types let you constrain values at the type level. A refined type is a base type plus a predicate — the compiler verifies the predicate holds, and erases the refinement in the emitted C#.


Quick Reference

SyntaxPurposeExample
§RTYPE{id:Name:base} (pred)Define a named refinement type§RTYPE{r1:NatInt:i32} (>= # INT:0)
§I{type:param} | (pred)Inline refinement on a parameter§I{i32:age} | (>= # INT:0)
§PROOF{id:desc} (expr)Proof obligation (assert a fact)§PROOF{p1:positive} (>= x INT:0)
#Self-reference (the value being refined)(>= # INT:0)

Named Refinement Types (§RTYPE)

Define a refinement type at module level. The predicate uses # to refer to the value being constrained.

Syntax

Calor
§RTYPE{id:Name:baseType} (predicate)
  • id — unique identifier (e.g., r1)
  • Name — the refinement type name, used in parameter declarations
  • baseType — the underlying type (i32, str, etc.)
  • predicate — a boolean expression using # for the value

Examples

Calor
§RTYPE{r1:NatInt:i32} (>= # INT:0)
§RTYPE{r2:Port:i32} (&& (>= # INT:1) (<= # INT:65535))
§RTYPE{r3:NonEmpty:str} (> (len #) INT:0)

These read as:

  • NatInt: an i32 that is non-negative
  • Port: an i32 between 1 and 65535
  • NonEmpty: a str with length greater than 0

Using Named Refinement Types

Once defined, use the name as a parameter type:

Calor
§RTYPE{r1:NatInt:i32} (>= # INT:0)

  §F{f001:Process:pub}
    §I{NatInt:count}
    §O{void}
  // count is guaranteed non-negative

The obligation engine creates a verification obligation for count — proving the refinement predicate holds given the function's preconditions.

Each Named Refinement Is Its Own Type

Named refinements are nominal. Two §RTYPEs over the same base type are different types, even when one predicate implies the other. Binding, passing, returning or assigning a Pos where a Nat is expected is a type error (Calor0202):

Calor
§M{m001:Ids}
  §RTYPE{r1:Nat:i32} (>= # INT:0)
  §RTYPE{r2:Pos:i32} (> # INT:0)
  §F{f001:ToNat:pub} (i32:v) -> Nat
    §R v
  §F{f002:Use:pub} (Pos:p) -> Nat
    §B{n:Nat} §C{ToNat} §A p §/C
    §R n

Binding the Pos directly is rejected with Calor0202:

Calor
§M{m001:Ids}
  §RTYPE{r1:Nat:i32} (>= # INT:0)
  §RTYPE{r2:Pos:i32} (> # INT:0)
  §F{f001:Use:pub} (Pos:p) -> Nat
    §B{n:Nat} p
    §R n

To convert on purpose, go through the base type: ToNat takes an i32 and returns Nat, and its return guard checks the value at run time. Operators still see a refinement as its base type, so (+ a p) is an i32. A conditional (? c a p) whose arms are two different refinements also has the base type.

A §W match is checked arm by arm. When the match is bound, returned or assigned where a Nat is expected, an arm that produces a Pos is Calor0202. In an §ASSIGN to a Nat local, an arm that produces a plain i32 is still accepted and guarded at run time. These checks apply everywhere the type checker looks: function and lambda bodies, class members (methods, constructors, property and indexer accessors, operators), §P arguments, §ASSIGN right-hand sides, and the bodies of §TR, §EACH and the other block statements.

Locals Inferred From a Refined Value

A §B without a type takes the type of its initializer, refinement included. After §B{~x} count with count: NatInt, x is a NatInt, exactly as if you had written §B{~x:NatInt} count. Every later write to x (§ASSIGN, inc/dec) has a runtime guard for NatInt. When refinement verification runs, the obligation engine can prove a write safe and drop its guard. It drops a guard only with a proof for that same refinement, and it skips writes it cannot match to one, such as a name a lambda parameter also uses; those keep their guard. Annotate the base type, §B{~x:i32} count, when the local should be free to leave the refinement. A parameter with only an inline refinement (§I{i32:a} | (pred)) has its base type, so a local inferred from it is a plain i32.

Four related rules keep a refined variable checked:

  • A lambda parameter without a type takes its type from the target delegate, also when the lambda is assigned to a delegate variable. If that type is NatInt, writes to the parameter are guarded too.
  • A variable with a refinement cannot be passed as a ref or out argument (Calor1104), because the callee's write could not be checked. Pass a base-typed temporary, then assign it back with §ASSIGN, which is guarded.
  • A mutable rebind of an existing variable (§B{~x} p after §B{~x} count) reassigns it, so it keeps the variable's named refinement and cannot change it (Calor0202). A parameter with an inline refinement cannot be rebound as a named refinement either.
  • A type pattern cannot name a refinement type: (is a Pos p) is Calor0202. Refinements erase at run time, so the test could only check the base type.

Inside class members the type checker reports only these refinement errors. Its other checks there are left to name binding and the C# compiler, as before, because it does not model inherited members, so in a class with a base class a bare call to a method the class does not declare is not checked. Members inside a §PP block are not type-checked; runtime guards still apply there. A write to a refined field or property has no runtime guard yet, so a setter's value and an indexer's parameters are typed as their base types.


Inline Refinements (|)

For one-off constraints, attach a predicate directly to a parameter with |:

Syntax

Calor
§I{baseType:paramName} | (predicate)

Examples

Calor
§F{f001:Divide:pub}
  §I{i32:a}
  §I{i32:b} | (!= # INT:0)         // b must be non-zero
  §O{i32}
  §R (/ a b)
Calor
§F{f002:SetPort:pub}
  §I{i32:port} | (&& (>= # INT:1) (<= # INT:65535))
  §O{void}
  // ...

Inline Refinements with Default Values

Inline refinements can coexist with default parameter values:

Calor
§I{i32:age} | (>= # INT:0) = INT:18

Self-Reference (#)

The # symbol refers to the value being constrained. It is only valid inside refinement predicates:

Calor
§RTYPE{r1:Positive:i32} (> # INT:0)     // # = the i32 value
§I{i32:x} | (>= # INT:0)                // # = x

Using # outside a refinement predicate is a compile error (SelfRefOutsidePredicate).


Proof Obligations (§PROOF)

A proof obligation asserts that a condition holds at a specific point in the function body. The obligation engine attempts to prove it using Z3.

Syntax

Calor
§PROOF{id:description} (boolean-expression)
§PROOF{id} (boolean-expression)
  • id — unique identifier
  • description — optional human-readable label

Examples

Calor
§F{f001:Transfer:pub}
  §I{i32:balance}
  §I{i32:amount} | (> # INT:0)
  §O{i32}
  §Q (>= balance amount)

  §PROOF{p1:non-negative} (>= (- balance amount) INT:0)

  §R (- balance amount)

Z3 proves this: given balance >= amount, then balance - amount >= 0. State the proof on the expression: the obligation solver does not yet track §B locals, so a proof about one is reported Unsupported.

Proof Obligation Statuses

StatusMeaningC# Output
DischargedZ3 proved the condition// PROVEN: proof obligation [p1] (guard dropped by default since 0.15; --keep-proven-guards keeps it)
FailedZ3 found a counterexampleRuntime guard (throws on violation)
TimeoutZ3 couldn't decide in timeRuntime guard (configurable by policy)
BoundaryPublic API — can't verify callersRuntime guard (always emitted)

Erasure

Refinement types are a compile-time construct. In the emitted C#, they are erased:

CalorEmitted C#
§RTYPE{r1:NatInt:i32} (>= # INT:0)(nothing — erased)
§I{NatInt:count}int count
§I{i32:x} | (>= # INT:0)int x
§PROOF{p1:check} (cond) (Discharged)// PROVEN: proof obligation [p1: check] by default; --keep-proven-guards emits the runtime guard instead
§PROOF{p1:check} (cond) (Failed)if (!(cond)) throw new InvalidOperationException(...)

The refinement constrains what values are valid. Since 0.15, a Discharged obligation's guard is replaced with a proof comment by default; pass --keep-proven-guards to keep the runtime guard and treat the verdict as a diagnostic only.


Obligation Engine

The obligation engine is the verification pipeline for refinement types:

  1. Generation — Walk the AST and create obligations for every refined parameter and §PROOF statement
  2. Solving — For each obligation, use Z3's assume-negate-check pattern:
    • Assume all preconditions (§Q)
    • Negate the obligation condition
    • If UNSAT → Discharged (proven)
    • If SAT → Failed (counterexample found)
    • If UNKNOWN → Timeout
  3. Guard Discovery — For failed obligations, discover the simplest guard that would discharge them
  4. Code Generation — Emit runtime guards based on obligation status and policy

Obligation Kinds

KindSource
RefinementEntryParameter with inline or named refinement
ProofObligation§PROOF statement

Public vs Private Functions

For public functions, caller constraints can't be verified — parameter refinement obligations are marked Boundary and always emit runtime guards. For private functions, the solver attempts full verification.


Obligation Policy

The obligation policy controls what happens for each obligation status. Three built-in policies:

Default

StatusAction
DischargedIgnore (proven, no guard needed)
FailedError (compilation fails)
TimeoutWarnAndGuard
BoundaryAlwaysGuard
UnsupportedWarnOnly

Strict

All non-discharged obligations are compilation errors. Use in CI for maximum safety.

Permissive

Failed obligations emit warnings and guards instead of errors. Use during development or migration.


Complete Example

This example writes the refinements inline. Named refinement types (§RTYPE) also work as arithmetic operands: (- balance amount) on two §RTYPE-typed parameters has the base type i32, not the refinement, because the difference can break the predicate.

Calor
§M{m001:Banking}
  §F{f001:Transfer:pub}
    §I{i32:balance} | (>= # INT:0)
    §I{i32:amount} | (> # INT:0)
    §O{i32}
    §Q (>= balance amount)                  // sufficient funds

    §PROOF{p1:balance-safe} (>= (- balance amount) INT:0)

    §R (- balance amount)

The proof states its condition on the expression itself. The obligation solver does not yet track local bindings, so a proof about a §B name is reported Unsupported. A default calor compile does not run the obligation solver; it keeps every runtime guard. The calor_refine MCP tool (action: "obligations") runs it.

The obligation engine:

  1. Creates Boundary obligations for balance and amount (public function)
  2. Creates a ProofObligation for p1
  3. Z3 proves p1: given balance >= 0, amount > 0, and balance >= amount, then balance - amount >= 0
  4. Emitted C#: a default calor compile does not solve obligations, so it emits runtime guards for balance, amount and p1. The emitter writes // PROVEN: proof obligation [p1: balance-safe] in place of the p1 guard only when the obligation was discharged in that same compilation (--keep-proven-guards keeps the guard even then)

See Also