navid/haze / 1e92eb578acb1bc4bfb552f7030892c35fcf41e6dd8819c459222586124949d6 / samples/baseline/10_named_contracts.hz

10_named_contracts.hz

← samples/baseline · 1022 bytes · raw · download

// 10: named contracts, pure functions in contracts, contract reuse.

pure fn even(n i32) bool => n % 2 == 0

contract Even(n i32) {
    pre even(n)
}

fn half(n i32) i32
    : Even(n)
    : post r => r * 2 == n
    => n / 2

// FactorialCond from the original sketch.
// Note: a static verifier cannot prove the multiplication stays in i32 from
// `r >= 1` alone; as runtime assertions it is checked on every call.
contract FactorialCond(n i32) {
    pre {
        n >= 0
        n <= 12
    }
    post r => r >= 1
}

fn factorial(n i32) i32 : FactorialCond(n) {
    if n <= 1
        return 1
    return n * factorial(n - 1)
}

fn main() {
    print(half(10))               // 5
    print(factorial(0))           // 1
    print(factorial(5))           // 120
    print(factorial(12))          // 479001600

    // Must be rejected:
    //
    // half(7)                    // pre `even(n)` violated
    // factorial(13)              // pre `n <= 12` violated
    // factorial(-1)              // pre `n >= 0` violated
}