navid/haze / faea9d9ec42bf4131a10e6646146d7408385322c6fc848aef1c66147380e7b58 / samples/baseline/09_contracts.hz

09_contracts.hz

← samples/baseline · 946 bytes · raw · download

// 09: inline contracts. One `: pre` / `: post` clause per line, before the `{`.
// A milestone-1 compiler can turn each clause into a runtime assertion.

fn clamp(x i32, lo i32, hi i32) i32
    : pre lo <= hi
    : post r => r >= lo && r <= hi
{
    if x < lo {
        return lo
    }
    if x > hi {
        return hi
    }
    return x
}

fn safe_div(a i32, b i32) i32
    : pre a >= 0
    : pre b > 0
    : post r => r >= 0 && r <= a
{
    return a / b
}

fn main() {
    print(clamp(15, 0, 10))       // 10
    print(clamp(-3, 0, 10))       // 0
    print(clamp(4, 0, 10))        // 4
    print(safe_div(17, 5))        // 3
    print(safe_div(0, 9))         // 0

    // Each of these must be rejected (compile time, or a runtime panic at milestone 1):
    //
    // clamp(1, 5, 2)             // pre `lo <= hi` violated
    // safe_div(10, 0)            // pre `b > 0` violated
    // safe_div(-1, 2)            // pre `a >= 0` violated
}