Guides · 01

Introduction

Vyi is a systems programming language in early alpha. The name is a respelling of the English word vie: to strive for something, to give it a try. Vyi compiles to WebAssembly, x86-64 Linux, and arm64 Linux. This guide is a tour of the language as it works today, written for someone who has programmed before and knows nothing about Vyi. It starts at hello world and goes through bindings, functions and methods, structs and enums, optionals and errors, control flow, known values and generics, interfaces, pointers and lifetimes, and calling C.

Each section is short and links to the guide that covers its topic in full.

Hello, world

Vyi
import { println } from "@fmt"

fn main() !u8 {
    println("hello, world")
    return Ok(0)
}

Save it as hello.vyi and run it:

sh
vyi run hello.vyi

A few things are already visible:

  • Imports bring in names directly. import { println } from "@fmt" makes println available as println. There is no module prefix to type.
  • main returns !u8, read as "a u8 or an error". Ok(0) is the success case, and the 0 becomes the program's exit code. Errors come up again below.
  • println prints any value that knows how to print itself. There's no format string: println(42) works, and println($"n = ${n}") puts a value into a string (guide 10).
  • Strings are UTF-8. Double quotes make a string; single quotes make a character, as in 'a'.

Bindings: con, mut, type

Vyi
import { println } from "@fmt"

type Cents = i32           // Cents is another name for i32

fn main() !u8 {
    con price = 250        // can't change; its type is i32
    con tax: Cents = 20    // type written out
    mut total = 0          // can change
    total += price
    total += tax
    println(total)         // prints 270
    return Ok(0)
}

Use con unless you need to reassign. Vyi has no int: every integer type states its width, from i8 to i64 and u8 to u64, plus iw and uw, which are as wide as a pointer. i32 is the usual choice.

No number type converts to another on its own. Adding an i32 to an i64 is an error until you write i64(a). Integer overflow stops the program in a debug build, which is the default, and wraps in a release build.

Guide 02, Values and bindings, covers bindings, types, literals, and conversions.

Functions and methods

fn declares a function. A method is a function with a receiver written before its name:

Vyi
import { println } from "@fmt"

struct Rect { width: i32, height: i32 }

fn (r: Rect) area() i32 {
    return r.width * r.height
}

fn main() !u8 {
    con r = Rect{ width: 3, height: 4 }
    println(r.area())   // prints 12
    return Ok(0)
}

Methods are declared on their own, outside the type, and any file can declare a method for any type. When you call r.area(), Vyi looks for area among the methods in scope where the call is written, and among the methods declared alongside Rect itself. This is also why imports bring in bare names: a method's name is in scope or it isn't.

Several functions can share a name when their parameter types differ. These are overloads, and a call picks one by the types of the arguments it passes. Functions are values, and closures capture what they use by value. Guide 04, Functions and closures, has the details.

Structs and enums

A struct groups named fields. An enum is a set of named variants, and a variant can carry data. match takes an enum apart:

Vyi
import { println } from "@fmt"

enum Shape {
    Dot,
    Square(i32),        // side
    Rect(i32, i32),     // width, height
}

fn (s: Shape) area() i32 {
    return match s {
        Dot:        0,
        Square(n):  n * n,
        Rect(w, h): w * h,
    }
}

fn main() !u8 {
    println(Shape.Square(4).area())    // prints 16
    println(Shape.Rect(2, 3).area())   // prints 6
    return Ok(0)
}

match must handle every variant, and it binds each variant's data to names (n, w, h). Its sibling switch compares a value against other values with ==.

Structs are values: assigning or passing a struct copies it. A struct can also be passed where a struct with a subset of its fields is expected. The copy keeps the shared fields and drops the rest:

Vyi
import { println } from "@fmt"

struct User    { name: [*con]u8, age: i32, city: [*con]u8 }
struct Address { name: [*con]u8, city: [*con]u8 }

fn printLabel(a: Address) {
    println(a.name)
    println(a.city)
}

fn main() !u8 {
    con user = User{ name: "ada", age: 36, city: "london" }
    printLabel(user)   // prints ada
                       // prints london
    return Ok(0)
}

printLabel takes an Address, and user is a User. The call copies name and city into an Address and leaves age out. This is the only conversion in Vyi that leaves data behind. Guide 03, Structs, enums, and tuples, covers both.

Absence is ?T

Vyi has no null. A value that might be missing has the optional type ?T:

Vyi
import { println } from "@fmt"

fn findAge(name: [*con]u8) ?i32 {
    if name == "ada" {
        return Some(36)
    }
    return None
}

fn main() !u8 {
    if Some(age) = findAge("ada") {
        println(age)                  // prints 36
    }
    println(findAge("bob") catch 0)   // prints 0
    return Ok(0)
}

if Some(age) = ... runs its block only when there is a value, and names it. catch 0 supplies a value for the absent case.

None and Some are not keywords. They are ordinary variants of the Optional enum that ?T stands for. When the expected type is an enum, you can write its variants without the enum's name, and that works for every enum, including your own.

Because absence has its own type, a pointer always points at something. A pointer that might be missing is an optional pointer, such as ?*mut T. Guides 07 and 09 cover optionals and pointers.

Errors are values

E!T means "an E or a T". A function that can fail returns one, and returns Err(...) when it fails:

Vyi
import { println } from "@fmt"

enum BankError { NotEnough }

fn withdraw(balance: i32, amount: i32) BankError!i32 {
    if amount > balance {
        return Err(NotEnough)
    }
    return Ok(balance - amount)
}

fn main() !u8 {
    println(try withdraw(100, 30))        // prints 70
    println(withdraw(100, 500) catch 0)   // prints 0
    return Ok(0)
}

At a call, you either pass the error on or deal with it:

  • try returns the error from the current function. Here that's main, and its !u8 is !T with the error type left out: the compiler works it out from the errors main can actually return, which is BankError.
  • catch handles it on the spot. withdraw(100, 500) catch 0 gives 0 when withdraw fails.

Errors travel as ordinary return values. Guide 07, Optionals and errors, and the error model reference give the full rules.

Control flow

if, switch, and match produce values, so you can use them on the right side of =:

Vyi
import { println } from "@fmt"

enum Light { Red, Yellow, Green }

fn main() !u8 {
    con degrees = 30
    con weather = if degrees > 25 { "warm" } else { "cool" }
    println(weather)   // prints warm

    con light = Light.Red
    con action = match light {
        Red:    "stop",
        Yellow: "slow",
        Green:  "go",
    }
    println(action)    // prints stop
    return Ok(0)
}

for is the only loop. It runs forever (for { }), while a condition holds (for cond { }), or once per item (for x in xs { }) over ranges, arrays, and any type that supports iteration:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut total = 0
    for n in 1..4 {       // 1, 2, 3
        total += n
    }
    println(total)        // prints 6
    return Ok(0)
}

1..4 stops before 4; 1...4 includes it.

Guide 05, Control flow, covers loops, labels, and switch.

Known values and generics

Vyi can run your code while it compiles. A value the compiler works out during compilation is called a known value. The term comes up throughout the guides: a known parameter must be given a known value, for example.

Types are known values too. A type has the type type, and a function can take a type and return a new one. That's how Vyi writes generics:

Vyi
import { println } from "@fmt"

fn Box(known T: type) type {
    return struct { value: T }
}

fn main() !u8 {
    con b = Box(i32){ value: 7 }   // Box(i32) runs while compiling
    println(b.value)               // prints 7
    return Ok(0)
}

Declarations can appear in any order, in any file. The compiler works out each known value when something needs it. Guide 11, Known values and generics, goes further.

Interfaces

An interface lists methods. Any type that has those methods can be used as that interface. There's no implements declaration:

Vyi
import { println } from "@fmt"

interface Speaker {
    fn (s: ~Speaker) speak() [*con]u8,
}

struct Dog { name: [*con]u8 }
fn (d: Dog) speak() [*con]u8 { return "woof" }

fn main() !u8 {
    con d = Dog{ name: "rex" }
    con s: Speaker = &d
    println(s.speak())   // prints woof
    return Ok(0)
}

con s: Speaker = &d turns a pointer to a Dog into a Speaker. At that point, Vyi picks the speak method that is in scope there, and the Speaker value keeps it. Calls through s then use that method. Guide 12, Interfaces, explains how this follows from methods living in scope.

Pointers and lifetimes

A pointer is valid only as long as the thing it points at exists. The compiler rejects any pointer that could outlive it, so returning the address of a local variable is an error. Passing a pointer into a call, or using it in the same block, is fine.

When a function returns a pointer, its signature says what the pointer is tied to. After the return type, write an apostrophe and the parameter in parentheses:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn main() !u8 {
    mut pt = Point{ x: 1, y: 2 }
    *xOf(&pt) = 10
    println(pt.x)   // prints 10
    return Ok(0)
}

'(p) means "valid as long as what p points at". '(a & b) ties the result to two parameters at once. A parameter that the function only reads or writes during the call needs nothing. A parameter that the function stores somewhere the caller can still reach is marked with what it's stored into, such as p: *mut Point '(s). The compiler checks every annotation against the body and against every call.

Guide 09, Pointers and memory, covers pointers, allocators, and the full rules for lifetimes.

Calling C

c_fn declares a C function. Import c from @c and call it as c.name. A c_fn with a body is written in Vyi and called with C's conventions, which is a quick way to try a call before you have a C library:

Vyi
import { c } from "@c"
import { println } from "@fmt"

c_fn add_two(a: c.int, b: c.int) c.int {
    return a + b
}

fn main() !u8 {
    println(c.add_two(2, 3))   // prints 5
    return Ok(0)
}

A c_fn without a body declares a function from a C library. Your program type-checks without the library; the library is needed only when the program is linked. Use C types in a c_fn's signature: optionals, tuples, and interfaces don't cross into C, and a struct crosses as a c_struct. Guide 15, C interop, covers every declaration form and how values are passed.

Where to go next

The command line at a glance

sh
vyi run file.vyi                        # build and run (WebAssembly by default)
vyi run --target x86-64-linux file.vyi  # build and run natively
vyi build -o out file.vyi               # build a program file named out
vyi build --emit=wat file.vyi           # write WebAssembly text
vyi check file.vyi                      # type-check only; --json for tools
vyi test                                # run every *.tests.vyi file

Options go before the file name. Guide 17, Tooling, covers the command line in full.