Contents Open

DocsWelcome to Sable

A Sable Tour

The whole language in one sitting: enough of every feature to start writing programs.

Tradition says a new language's first program prints "Hello, world!". In Sable that is three lines and a module name:

Sable
module Hellofn main() {    print("Hello, world!")}
Hello, world!

Every file starts with a module declaration, and a program starts at main. You don't import anything for print, and you don't end statements with semicolons.

This tour shows you enough of every part of the language to start writing programs. Don't worry if something isn't fully explained: each section links to the guide chapter that covers it properly. To try the examples, put them inside a main function in a file and run it with sable run file.sb, as Getting Started describes.

Simple Values#

Use let to make a constant and var to make a variable. A constant's value is set once; a variable's may change.

Sable
var myVariable = 42myVariable = 50let myConstant = 42

Every value has a type, but you rarely have to write it: the compiler infers it from the initial value. myVariable above is an Int. When the initial value doesn't say enough, or there isn't one, write the type after a colon:

Sable
let implicitInteger = 70let implicitDouble = 70.0let explicitDouble: F64 = 70

Sable's numeric types have short names: Int and UInt are the machine word, I8 to I128 and U8 to U128 are fixed widths, and F16, F32, F64 and BF16 are floating point. Values never convert to another type implicitly. You convert explicitly, with as or a method:

Sable
let label = "The width is "let width = 94let widthLabel = label + width.toString()

The simplest way to put values in a string is interpolation: write the value in parentheses after a backslash. A colon inside the parentheses adds a format spec:

Sable
let apples = 3let oranges = 5print("I have \(apples + oranges) pieces of fruit.")print("\(3.14159:.2) \(255:#06x) \(1234567:,)")
I have 8 pieces of fruit.3.14 0x00ff 1,234,567

Use three double quotes for a string that spans lines. The indentation of the closing quotes is removed from every line:

Sable
let quotation = """    I said "I have \(apples) apples."    And then I said "I have \(apples + oranges) pieces of fruit."    """

Arrays are written with brackets. Sable has a family of array types, and the suffix after the element type says what the array can do: String[] is fixed once it is made, and String[>..] can grow.

Sable
var fruits: String[>..] = ["strawberries", "limes", "tangerines"]fruits[1] = "grapes"fruits.append("blueberries")print(fruits)
["strawberries", "grapes", "tangerines", "blueberries"]

A dictionary is written [Key: Value], and keeps its entries in the order they were inserted:

Sable
var occupations = [    "Malcolm": "Captain",    "Kaylee": "Mechanic",]occupations["Jayne"] = "Public Relations"

An empty array or dictionary needs its type from somewhere, such as an annotation:

Sable
let emptyArray: String[>..] = []let emptyDictionary: [String: F64] = [:]

The guide covers these in The Basics, Strings and Characters and Arrays and Collections.

Control Flow#

Use if and match to choose, and for, while and repeat to loop. Parentheses around a condition are optional; braces around a body are required, and the opening brace goes on the same line.

Sable
let individualScores = [75, 43, 103, 87, 12]var teamScore = 0for score in individualScores {    if score > 50 {        teamScore += 3    } else {        teamScore += 1    }}print(teamScore)
11

Where a value is wanted, an if with an else gives one:

Sable
let scoreDecoration = if teamScore > 10 { "🎉" } else { "" }print("Score: \(teamScore) \(scoreDecoration)")

A value that might be missing is an optional, written with a ? after its type. It holds either a value or none. if let unwraps it, running the body only when there is a value. ?? gives a default instead:

Sable
let optionalName: String? = "John Appleseed"if let name = optionalName {    print("Hello, \(name)")}let nickname: String? = nonelet fullName = "John Appleseed"print("Hi \(nickname ?? fullName)")
Hello, John AppleseedHi John Appleseed

match compares a value against patterns. It can bind parts of the value, test them with where, and is an expression as well as a statement. It must cover every possible value, so this one needs a default:

Sable
let vegetable = "red pepper"let comment = match vegetable {    case "celery" => "Add some raisins and make ants on a log."    case "cucumber", "watercress" => "That would make a good tea sandwich."    case let x where x.hasSuffix("pepper") => "Is it a spicy \(x)?"    default => "Everything tastes good in soup."}print(comment)
Is it a spicy red pepper?

for-in goes through an array, a dictionary (as key and value pairs) or a range. ..< makes a range that leaves out its upper bound, and ... one that includes it:

Sable
let interestingNumbers = [    "Prime": [2, 3, 5, 7, 11, 13],    "Fibonacci": [1, 1, 2, 3, 5, 8],    "Square": [1, 4, 9, 16, 25],]var largest = 0for (_, numbers) in interestingNumbers {    for number in numbers {        if number > largest {            largest = number        }    }}print(largest)var total = 0for i in 0..<4 {    total += i}print(total)
256

while repeats while a condition holds; repeat-while checks it after each pass, so the body runs at least once:

Sable
var n = 2while n < 100 {    n *= 2}var m = 2repeat {    m *= 2} while m < 100print("\(n) \(m)")
128 128

See Control Flow and Pattern Matching.

Functions and Closures#

Declare a function with fn, its parameters with their types, and its result type after ->:

Sable
fn greet(person: String, day: String) -> String {    return "Hello \(person), today is \(day)."}print(greet(person: "Bob", day: "Tuesday"))

A parameter's name is also its label at the call, and as in C# the label may be left out: greet("Bob", "Tuesday") works too. Write a different external label before the parameter name, or _ for none:

Sable
fn greet(_ person: String, on day: String) -> String {    return "Hello \(person), today is \(day)."}print(greet("John", on: "Wednesday"))

A function whose body is one expression can write it after =>. Use a tuple to return several values; its elements can be named, or read by position:

Sable
fn lessThanTen(number: Int) -> Bool => number < 10fn calculateStatistics(_ scores: Int[]) -> (min: Int, max: Int, sum: Int) {    var min = scores[0]    var max = scores[0]    var sum = 0    for score in scores {        if score > max {            max = score        } else if score < min {            min = score        }        sum += score    }    return (min: min, max: max, sum: sum)}let statistics = calculateStatistics([5, 3, 100, 3, 9])print(statistics.sum)print(statistics.2)
120120

Functions nest, and a nested function can use the variables of the function around it. Functions are values, so one can return another, or take another as an argument:

Sable
fn makeIncrementer() -> (Int) -> Int {    fn addOne(number: Int) -> Int {        return 1 + number    }    return addOne}fn hasAnyMatches(_ list: Int[], condition: (Int) -> Bool) -> Bool {    for item in list {        if condition(item) {            return true        }    }    return false}let increment = makeIncrementer()print(increment(7))print(hasAnyMatches([20, 19, 7, 12], condition: lessThanTen))
8true

A closure is a function written as an expression: its parameters, =>, and its body. When the closure is a call's last argument, you can write it after the parentheses in braces, as a trailing closure, and refer to its parameters as $0, $1 and so on, or name them before in:

Sable
let numbers = [20, 19, 7, 12]let triple = (x: Int) => x * 3print(numbers.map(triple))print(numbers.filter { $0 % 2 == 1 })print(numbers.sorted { a, b in a > b })
[60, 57, 21, 36][19, 7][20, 19, 12, 7]

See Functions and Closures.

Objects and Classes#

A class is declared with class. Its stored properties are declared like variables, and its initialiser is init. You make an instance by calling the class's name:

Sable
class NamedShape {    var numberOfSides: Int = 0    var name: String    init(name: String) {        self.name = name    }    fn simpleDescription() -> String {        return "A shape with \(numberOfSides) sides."    }}let shape = NamedShape(name: "a shape")shape.numberOfSides = 7print(shape.simpleDescription())
A shape with 7 sides.

Classes are reference types: two variables can refer to the same object, and === asks whether they do. Objects are freed by reference counting, as soon as the last reference to them goes away.

A subclass names its superclass after a colon. Methods are not virtual unless the class says they may be overridden, with open, and an override must say override:

Sable
open class Shape {    var name: String    init(name: String) {        self.name = name    }    open fn simpleDescription() -> String => "A shape called \(name)."}class Square: Shape {    var sideLength: F64    init(sideLength: F64, name: String) {        self.sideLength = sideLength        super.init(name: name)    }    fn area() -> F64 => sideLength * sideLength    override fn simpleDescription() -> String {        return "A square with sides of length \(sideLength)."    }}let test = Square(sideLength: 5.0, name: "my test square")print(test.area())print(test.simpleDescription())
25.0A square with sides of length 5.0.

A property can be computed, with a getter and a setter, rather than stored. A stored property can have observers that run around each change:

Sable
class EquilateralTriangle {    var sideLength: F64 = 0.0    var perimeter: F64 {        get => 3.0 * sideLength        set { sideLength = newValue / 3.0 }    }}class StepCounter {    var steps: Int = 0 {        willSet { print("about to set steps to \(newValue)") }        didSet { print("added \(steps - oldValue) steps") }    }}let counter = StepCounter()counter.steps = 200counter.steps += 30
about to set steps to 200added 200 stepsabout to set steps to 230added 30 steps

Optional chaining, ?., reaches through an optional: if the optional is none, so is the whole expression.

Sable
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")let sideLength = optionalSquare?.sideLength

See Structures and Classes, Properties and Initialization and Deinitialization.

Enumerations, Unions and Structures#

Sable has two kinds of "enum", and keeps them apart on purpose. An enum is a named integer, with an optional underlying type; a case without a value takes the one after the case before it:

Sable
enum Rank: U8 {    Ace = 1    Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten    Jack, Queen, King    fn simpleDescription() -> String {        return match self {            case .Ace => "ace"            case .Jack => "jack"            case .Queen => "queen"            case .King => "king"            default => "\(self as U8)"        }    }}enum Suit { Spades, Hearts, Diamonds, Clubs }print(Rank.Ace as U8)print(Rank.Queen.simpleDescription())print(3 as Rank)
1queenThree

Where the type is known, a case can be written with just a leading dot, .Ace. An enum marked @flags is a set of bit flags:

Sable
@flagsenum Permissions: U32 {    Read    Write    Execute}let permissions: Permissions = [.Read, .Write]print(permissions.contains(.Write))

A union is a tagged sum: each case can carry values of its own, and match takes them apart:

Sable
union ServerResponse {    Result(sunrise: String, sunset: String)    Failure(message: String)}let success = ServerResponse.Result(sunrise: "6:00 am", sunset: "8:09 pm")let failure: ServerResponse = .Failure(message: "Out of cheese.")for response in [success, failure] {    match response {        case .Result(let sunrise, let sunset) => print("Sunrise is at \(sunrise) and sunset is at \(sunset).")        case .Failure(let message) => print("Failure...  \(message)")    }}
Sunrise is at 6:00 am and sunset is at 8:09 pm.Failure...  Out of cheese.

Unions can also be structural, written in place without a declaration, such as Int | String. Testing one with is narrows it.

A struct is like a class, but it is a value: assigning it or passing it copies it. It gets a memberwise initialiser, and can also be made with a record literal, which names every field. A method that changes a struct is marked mutating:

Sable
struct Card {    var rank: Rank    var suit: Suit    fn simpleDescription() -> String {        return "The \(rank.simpleDescription()) of \(suit)"    }}struct Point {    var x: F64    var y: F64    mutating fn moveBy(dx: F64, dy: F64) {        x += dx        y += dy    }}let threeOfSpades = Card(rank: .Three, suit: .Spades)print(threeOfSpades.simpleDescription())let a = Point { x: 1, y: 2 }var b = ab.moveBy(dx: 10, dy: 0)print("\(a.x) \(b.x)")
The 3 of Spades1.0 11.0

Changing b left a alone: b is a copy. See Enums and Unions and Structures and Classes.

Concurrency#

Mark a function that runs asynchronously with async, and call it with await:

Sable
async fn fetchUserID(from server: String) -> Int {    if server == "primary" {        return 97    }    return 501}async fn fetchUsername(from server: String) -> String {    let userID = await fetchUserID(from: server)    if userID == 501 {        return "John Appleseed"    }    return "Guest"}

async let starts work alongside the code that follows, and the value is awaited where it is read:

Sable
async fn connectUser(to server: String) {    async let userID = fetchUserID(from: server)    async let username = fetchUsername(from: server)    let greeting = await "Hello \(username), user ID \(userID)"    print(greeting)}

A task group runs any number of child tasks and gives their results as they finish. Children can't outlive the scope that started them: this is structured concurrency.

Sable
let userIDs = await withTaskGroup(of: Int.self) { group in    for server in ["primary", "secondary", "development"] {        group.spawn {            return await fetchUserID(from: server)        }    }    var results: Int[>..] = []    for await result in group {        results.append(result)    }    return results}

An actor is like a class whose state only one task can touch at a time. Calling into it from outside awaits its turn:

Sable
actor ServerConnection {    private var activeUsers: Int[>..] = []    fn connect() -> Int {        activeUsers.append(97)        return activeUsers.count    }}@mainasync fn main() {    await connectUser(to: "primary")    let connection = ServerConnection()    let count = await connection.connect()    print(count)}
Hello Guest, user ID 971

main itself may be async. Values that cross from one task or actor to another must be Sendable, which the compiler checks. See Concurrency.

Protocols and Extensions#

Declare a protocol with protocol. Classes, structs, unions and enums can all conform to one:

Sable
protocol ExampleProtocol {    var simpleDescription: String { get }    mutating fn adjust()}class SimpleClass: ExampleProtocol {    var simpleDescription: String = "A very simple class."    fn adjust() {        simpleDescription += "  Now 100% adjusted."    }}struct SimpleStructure: ExampleProtocol {    var simpleDescription: String = "A simple structure"    mutating fn adjust() {        simpleDescription += " (adjusted)"    }}

A struct's adjust is mutating because it changes the struct; a class's needn't be, because a method can always change the object it is called on.

An extension adds members to an existing type, including one you didn't write, or makes it conform to a protocol. An extension of a protocol gives every conforming type a default implementation:

Sable
protocol Describable {    fn describe() -> String}extension Int: Describable {    fn describe() -> String => "The number \(self)"}extension Int {    var squared: Int => self * self}print(7.describe())print(7.squared)
The number 749

Conformance is always declared: a type that happens to have the right members does not conform by accident.

A protocol can be used two ways. some P means "one particular type that conforms to P", known at compile time and specialised for, at no cost. any P is a box that can hold any conforming type, called through a table at run time; an array of different shapes needs one:

Sable
protocol Shape {    var area: F64 { get }}struct Circle: Shape {    var radius: F64    var area: F64 => 3.0 * radius * radius}struct Rect: Shape {    var width: F64    var height: F64    var area: F64 => width * height}fn printArea(_ shape: some Shape) {    print(shape.area)}let shapes: (any Shape)[] = [Circle(radius: 1), Rect(width: 2, height: 5)]for s in shapes {    printArea(s)}
3.010.0

See Protocols and Extensions.

Error Handling#

An error can be any type; usually it is a union of the ways something can fail. A function says what it may throw in its signature, throws(E), and every call to it is marked with try:

Sable
union PrinterError {    OutOfPaper    NoToner    OnFire}fn send(job: Int, toPrinter printerName: String) throws(PrinterError) -> String {    if printerName == "Never Has Toner" {        throw .NoToner    }    return "Job sent"}

Handle errors with do-catch. Each catch can match a case, and a bare catch takes the rest, calling the error error:

Sable
do {    let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")    print(printerResponse)    print(try send(job: 1440, toPrinter: "Never Has Toner"))} catch .OnFire {    print("I'll just put this over here, with the rest of the fire.")} catch {    print(error)}
Job sentPrinterError.NoToner

Because the error type is known, a do whose catch clauses don't cover every case of it, and has no bare catch, is a compile error. try? turns an error into none, and try ... catch gives a fallback value inline:

Sable
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")let response = try send(job: 1885, toPrinter: "Never Has Toner") catch { "not sent" }

defer runs code when the current scope ends, however it ends: by returning, by throwing, or by reaching its end:

Sable
fn fridgeContains(_ food: String) -> Bool {    let fridgeContent = ["milk", "eggs", "leftovers"]    defer {        print("fridge closed")    }    return fridgeContent.contains(food)}print(fridgeContains("banana"))
fridge closedfalse

Errors in Sable are ordinary return values, not exceptions: throwing doesn't unwind the stack. For a broken invariant there are panics, such as precondition and fatalError, which stop the program and can't be caught. See Error Handling.

Generics#

Write a type parameter in angle brackets to make a generic function or type:

Sable
fn makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> Item[>..] {    var result: Item[>..] = []    for _ in 0..<numberOfTimes {        result.append(item)    }    return result}print(makeArray(repeating: "knock", numberOfTimes: 4))
["knock", "knock", "knock", "knock"]

Generic types work the same way:

Sable
struct Stack<Element> {    private var items: Element[>..] = []    mutating fn push(_ item: Element) {        items.append(item)    }    mutating fn pop() -> Element? {        return items.isEmpty ? none : items.removeLast()    }}var stack = Stack<Int>()stack.push(1)stack.push(2)print(stack.pop() ?? 0)
2

Constrain a type parameter with a protocol after a colon, or with a where clause:

Sable
fn allEqual<T>(_ items: T[:]) -> Bool where T: Equatable {    for item in items {        if item != items[0] {            return false        }    }    return true}print(allEqual([1, 1, 1]))

T[:] is a slice, a view of any kind of array. Generic code is specialised for each type it is used with, so it is as fast as code written for that type. See Generics.

Memory#

What sets Sable apart is how much it lets you say about memory, and how much it checks. Most of the time you don't think about it: structs are copied, objects are reference-counted. When you want more control, three tools are close at hand.

A @noncopy struct can't be copied, only moved. That suits a resource, such as a file or a connection, which must be closed exactly once. Its deinit runs when its owner is done with it. using binds one for the rest of the block, and a consuming parameter takes it over:

Sable
@noncopystruct Connection {    let id: Int    fn send(_ message: String) {        print("[\(id)] \(message)")    }    deinit {        print("connection \(id) closed")    }}fn hangUp(_ connection: consuming Connection) {    connection.send("goodbye")}fn main() {    let first = Connection { id: 1 }    first.send("hello")    hangUp(first)    using let second = Connection { id: 2 }    second.send("hi")}
[1] hello[1] goodbyeconnection 1 closed[2] hiconnection 2 closed

After hangUp(first), first has moved; using it again is a compile error (S3057).

A region is an arena: values allocated in it are freed together, all at once, when the region's block ends. alloc gives a reference, Node&, and the compiler infers that every such reference is rooted in the region, so none can escape it:

Sable
struct Node {    var value: Int    var next: Node&?}fn sumList(_ head: Node&) -> Int {    var total = 0    var current: Node&? = head    while let node = current {        total += node.value        current = node.next    }    return total}fn buildAndSum(_ count: Int) -> Int {    region scratch {        var head = scratch.alloc(Node { value: 0, next: none })        for i in 1..<count {            head = scratch.alloc(Node { value: i, next: head })        }        return sumList(head)    }}print(buildAndSum(5))
10

Returning head itself from buildAndSum would be an error (S3061): the region dies when the block ends, and the compiler says so. No lifetime annotations were needed for it to know.

For classes, weak and unowned references break the cycles that reference counting can't free on its own:

Sable
class Owner {    var pet: Pet? = none}class Pet {    weak var owner: Owner? = none}
Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.