Why Vx is easier to read than C++ and Rust

TL;DR — People read code more often than they write it. Vx keeps the parts of C++ and Rust that read well: types after names, trait bounds, and macros that match tokens. It leaves out the parts that make a reader stop: the turbofish, async functions, lifetime markers, constraint strings of inline assembly, #[cfg] and the C preprocessor. Parallel code is a loop with across blocks and across lanes, and a function says what it needs and what it gives in requires and ensures, which the compiler proves. Each section below shows one piece of code in C++, Rust and Vx. The last section says what each choice costs.

A reader of a function wants three answers fast: what it takes, what it gives, and what it does. Each piece of syntax that answers none of them is noise. This post goes through the places where C++ or Rust adds such noise, and shows what Vx writes there.

Type arguments with no turbofish

Rust needs ::< before the type arguments of a call in an expression:

let v = Vec::<i32>::new();
let n = "42".parse::<i32>().unwrap();
let all = words.iter().collect::<Vec<_>>();

C++ has no turbofish, but in a template it needs typename and .template to say what a name is:

template <typename T>
void show(const T& t) {
  typename T::value_type first = t.front();
  auto second = t.template get<1>();
}

Vx writes the type arguments after the name, as a type does:

import std::vec;

fn first_or<T>(v : &Vec<T>, fallback : T) -> T {
  if v.len() > 0 {
    return *v.get_ref(0);
  }
  return fallback;
}

fn main() -> i32 {
  let mut v = Vec<i32>::new();
  v.push(7);
  println!("{}", first_or<i32>(&v, 0));
  return 0;
}

The turbofish exists for a reason. A parser that does not know the names cannot tell f<T>(x), a call, from (f < T) > (x), two comparisons. Rust chose to make every reader type ::<. Vx asks the parser to know a little more: after the name of a variable or a parameter in scope, < is a comparison, and after any other name it starts the type arguments. So both(a < b, c > (d)) passes two bools.

A function that waits is a normal function

In Rust, a function that waits for a channel must be async. Each function that calls it must be async too, up to a runtime such as tokio:

use tokio::sync::mpsc::Receiver;

async fn next_value(rx: &mut Receiver<i64>) -> i64 {
    rx.recv().await.unwrap_or(-1)
}

#[tokio::main]
async fn main() {
    let (tx, mut rx) = tokio::sync::mpsc::channel(1);
    tokio::spawn(async move { tx.send(42).await.unwrap() });
    println!("got {}", next_value(&mut rx).await);
}

A C++20 coroutine does the same with co_await and a task type as the return type. Such a function has a "colour", and a program must keep the two colours apart. In Vx, a function that waits is a normal function. A tasks block starts tasks, and the block waits for them before it ends:

import core::result;
import std::sync::channel;

// A normal function that waits. A task and the main code call it the same way.
fn next_value(rx : &Receiver<i64>) -> i64 {
  return match rx.recv() {
    Result<i64, RecvError>::Ok(v) => {
      v
    }
    Result<i64, RecvError>::Err(_e) => {
      -1
    }
  };
}

fn main() -> i32 {
  let (tx, rx) = channel<i64>(1);
  let got = tasks {
    spawn {
      let t = tx;
      let _sent = t.send(42);
    };
    next_value(&rx)
  };
  println!("got {}", got);
  return 0;
}

next_value has the same signature that it would have in a program with no tasks. A borrow that lives across a wait is a borrow across a call, so the borrow checker needs no new rule.

References with no lifetime markers

When a Rust function returns a reference, its signature says which argument the result borrows from:

fn longer<'a>(a: &'a Vec<i64>, b: &'a Vec<i64>) -> &'a Vec<i64> {
    if a.len() >= b.len() { a } else { b }
}

C++ has no marker, and it has no check either. A caller can keep the result after the vector is gone:

const std::vector<long>& longer(const std::vector<long>& a,
                                const std::vector<long>& b) {
  return a.size() >= b.size() ? a : b;
}

Vx has no lifetime syntax, and it checks the borrow. The compiler reads the body, and finds that the result points into a or b:

import std::vec;

// The result points into `a` or `b`. No marker says so: the compiler reads the body.
fn longer(a : &Vec<i64>, b : &Vec<i64>) -> &Vec<i64> {
  if a.len() >= b.len() {
    return a;
  }
  return b;
}

fn main() -> i32 {
  let mut x = Vec<i64>::new();
  x.push(1i64);
  let mut y = Vec<i64>::new();
  y.push(2i64);
  y.push(3i64);
  let l = longer(&x, &y);
  println!("longer has {}", l.len());
  return 0;
}

A signature can still say what the result does not borrow. A borrow clause, such as ensures !reaches(return, *key), states that the result never points at key. The caller then reads the fact in the signature.

Parallel code as blocks and lanes

A GPU kernel in CUDA C++ is a function of its own. Its loop uses blockIdx and threadIdx, and the call says how many blocks and threads to start:

__global__ void scale(float* grid, int cols) {
  int y = blockIdx.x;
  for (int x = threadIdx.x; x < cols; x += blockDim.x)
    grid[y * cols + x] = grid[y * cols + x] * 2.0f + y;
}

scale<<<64, 256>>>(device_grid, 300);

Rust has no GPU code in the language. In Vx, the kernel is the loop that the program would write anyway, with across blocks and across lanes(256) after the ranges:

fn main() -> i32 {
  let mut grid = transfer(Tensor<f32, [64, 300]>::fill(1.0), Memory::HBM);
  spawn on(Topology::Device) {
    for y in 0..64 across blocks {
      for x in 0..300 across lanes(256) {
        grid[y][x] = grid[y][x] * 2.0 + (y as f32);
      }
    }
  }
  let back = transfer(grid, Memory::CPU_DRAM);
  println!("corner {}, last row {}", back[0][0], back[63][299]);
  return 0;
}

The compiler checks that two passes cannot write the same element (E6032), so the loop has no data race. The meaning does not depend on across: remove it, and the loops run one pass at a time with the same result. On a computer with no GPU, the same program runs on the threads of the CPU.

A bound names a trait

A C++20 concept lists the expressions that must compile for a type:

template <typename T>
concept Ordered = requires(const T& a, const T& b) {
  { a > b } -> std::convertible_to<bool>;
};

template <Ordered T>
T largest(T a, T b) { return a > b ? a : b; }

Rust names a trait, which lists methods with their types. Vx takes this from Rust:

import core::cmp;

fn largest<T : PartialOrd>(a : T, b : T) -> T {
  if a > b {
    return a;
  }
  return b;
}

fn main() -> i32 {
  println!("{} {}", largest(3, 7), largest(2.5, 1.5));
  return 0;
}

The bound says what largest needs in one word, and an error names the trait that a type does not implement.

A signature says what the function needs and gives

In Vx, requires states what must be true when a caller calls the function, and ensures states what is true when it returns. An SMT solver, z3, proves both at compile time:

fn clamp(x : i32, hi : i32) -> i32
    requires hi >= 0
    ensures return >= 0
    ensures return <= hi
{
  if x < 0 {
    return 0;
  }
  if x > hi {
    return hi;
  }
  return x;
}

fn checked(v : i32, limit : i32) -> i32 {
  if limit >= 0 {
    return clamp(v, limit);
  }
  return 0;
}

fn main() -> i32 {
  return checked(12, 10) - 10;
}

A caller that cannot show hi >= 0 gets an error at the call, not a crash when the program runs:

Error[E8006] at contract.vx:23:10: this call to 'clamp' may not meet its precondition `hi >= 0`:
the compiler cannot prove it from what is known here

So a reader of clamp needs only its signature to know that the result is between 0 and hi, and the compiler keeps that true. C++26 adds pre and post to a declaration, and a build can check them when the program runs. Stable Rust has no contracts.

Inline MLIR in place of inline assembly

Inline assembly in C++ puts the operands in constraint strings, and the instruction is for one CPU:

int count_ones(int x) {
  int r;
  asm("popcnt %1, %0" : "=r"(r) : "r"(x));
  return r;
}

Rust's asm! names the operands, but the instruction and the register sizes are still x86's:

fn count_ones(x: u32) -> u32 {
    let r: u32;
    unsafe { core::arch::asm!("popcnt {r:e}, {x:e}", x = in(reg) x, r = out(reg) r) };
    r
}

Vx puts MLIR in the function. Each input has a name and a type, the block says the type that it gives, and it lists the dialects that it uses:

fn count_ones(x : i32) -> i32 {
  return mlir!(inputs : (%a = x : i32), returns : i32, dialects : ["math"]) {
    %r = math.ctpop %a : i32
    macro.yield %r : i32
  };
}

math.ctpop is one operation for every target, not an x86 instruction. The compiler checks the list of dialects against the body (E8010). A block outside unsafe must be on a short list of operations that the compiler verifies as safe, and math.ctpop is on it.

No attributes and no preprocessor

Rust selects code for a machine with an attribute on each item, and C++ with the preprocessor:

#[cfg(target_feature = "avx512f")]
fn floats_per_step() -> i32 { 16 }

#[cfg(not(target_feature = "avx512f"))]
fn floats_per_step() -> i32 { 4 }
#ifdef __AVX512F__
constexpr int floats_per_step = 16;
#else
constexpr int floats_per_step = 4;
#endif

Vx has no attributes, and no preprocessor. The code for each machine is ordinary Vx, in the function that needs it. The condition is a value: the topology that the code compiles for.

// The code for each machine is ordinary Vx, in the function that needs it.
fn floats_per_step() -> i32 {
  if comptime Topology::Current == Topology::CPU_AVX512 {
    return 16;
  } else {
    return 4;
  }
}

fn main() -> i32 {
  println!("{} floats per step", floats_per_step());
  return 0;
}

Vx has macros, as Rust does. A macro_rules macro matches patterns of tokens, and the compiler checks the code that it writes as if you typed it. There is no #define that pastes text, and no #include:

macro_rules clamp {
  ($x : expr, $low : expr, $high : expr) => {
    if $x < $low {
      $low
    } else {
      clamp!($x, $high)
    }
  };
  ($x : expr, $high : expr) => {
    if $x > $high {
      $high
    } else {
      $x
    }
  };
}

What each choice costs

In one table

C++RustVx
Type arguments in a callf<int>(x), t.template get<1>()f::<i32>(x)f<i32>(x)
A function that waitsa coroutine, co_awaitasync fn, .awaita normal function
A returned referenceno marker, no check&'a Tno marker, checked
A loop on a GPUa kernel and <<<64, 256>>>not in the languagefor y in 0..64 across blocks
A bound on a type parametera concept of expressionsa traita trait
What a function needs and givespre, post in C++26, which a build can check at run timenone in stable Rustrequires, ensures, proved at compile time
One operation the language has no syntax forasm with constraint stringsasm!, one CPUmlir!, named and typed
Code for one machine#ifdef#[cfg(..)]if comptime Topology::Current == ..
Macros#define, textmacro_rules!, tokensmacro_rules, tokens

Vx is Apache 2.0 with the LLVM exception — install it and try the examples.