Oxeon / Examples / Ownership and borrowing

Ownership and borrowing

Moves, borrows, lifetimes and Drop in Oxeon, which follows Rust’s ownership rules.

Partly works today

The borrow checker enforces these rules today: moves, Copy types, & and &mut, and conflicting borrows, with non-lexical lifetimes. The functions here don’t compile yet because they use String. Not yet: lifetimes in signatures (longest, Parser<'src>) and Drop.

Oxeon follows Rust’s ownership model, checked at compile time. Passing a String by value moves it: after let b = a;, using a is an error. &T borrows a value to read it, and &mut T borrows it exclusively to change it.

Lifetimes connect borrows. In longest, 'a says the result borrows from the inputs, so it can’t outlive them. A struct can hold borrows too (Parser<'src>).

Drop runs code when a value goes out of scope, at a predictable point.

The borrow checker uses non-lexical lifetimes, as Rust’s does, and runs on Oxeon’s MIR: a borrow lasts until its last use, not to the end of its scope.

05_ownership.ox

examples/syntax/05_ownership.ox
// Moves, borrows, lifetimes and Drop. Checked exactly like Rust.

fn take(s: String) -> usize {
    s.len()
} // `s` is dropped here

fn borrow(s: &String) -> usize {
    s.len()
}

fn mutate(s: &mut String) {
    s.push('!');
}

fn ownership() {
    let a = String::from("mod");
    let b = a; // `a` moved into `b`; using `a` is now a compile error
    let n = borrow(&b);

    let mut c = b.clone();
    mutate(&mut c);
    let m = take(c);
}

// Lifetimes tie the output borrow to the inputs.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

// Structs can hold borrows.
struct Parser<'src> {
    input: &'src str,
    pos: usize,
}

impl<'src> Parser<'src> {
    fn rest(&self) -> &'src str {
        &self.input[self.pos..]
    }
}

struct Guard {
    name: String,
}

impl Drop for Guard {
    fn drop(&mut self) {
        // runs deterministically when the value goes out of scope
    }
}