Contents Open

DocsLanguage Guide

The Basics

Constants and variables, the built-in types, type inference, tuples, optionals and assertions.

Sable gives you the building blocks you would expect from a language in the C family: integers of several widths, floating-point numbers, Booleans, strings, and the collections you will meet in Arrays and Collections. On top of those it adds tuples, which group values without declaring a type, and optionals, which say in the type whether a value may be missing.

Sable is type-safe. Every value has one type, fixed at compile time, and values never change type behind your back: an I32 doesn't silently become an I64, and a String is never none. Type inference means you rarely have to write those types down. This chapter covers how values are named, the basic types, and the tools for stating what must be true while a program runs.

Constants and Variables#

A constant or a variable gives a name to a value. Declare a constant with let and a variable with var:

Sable
let maximumNumberOfLoginAttempts = 10var currentLoginAttempt = 0

A constant's value can't change once it is set. A variable's can be changed as often as you like:

Sable
currentLoginAttempt += 1maximumNumberOfLoginAttempts = 11   // error[S3010]: a 'let' can't be assigned

Use let for every value that doesn't need to change, and var only for those that do. The lints that sable lint runs point out a var that is never changed, and suggest let.

You can declare several values on one line, separated by semicolons, though putting each on its own line is usually clearer:

Sable
var x = 0.0; var y = 0.0; var z = 0.0

Type Annotations#

Write a type annotation after a colon to say what type a constant or variable holds:

Sable
var welcomeMessage: StringwelcomeMessage = "Hello"

You need an annotation when there is no initial value, or when the initial value alone would give a different type than the one you want:

Sable
let ratio: F64 = 3        // 3.0, not the Int 3let level: U8 = 200

Definite Assignment#

A constant or variable declared without a value must be given one before it is read. Sable doesn't fill it with zero: reading it first is an error.

Sable
var total: Intprint(total)
error[S6008]: 'total' is read here before anything assigns to it

The compiler follows every path through the code, so a variable assigned on each branch of an if counts as assigned:

Sable
var limit: Intif isPremium {    limit = 100} else {    limit = 10}print(limit)

A let gets its value where it is declared; assigning one afterwards is an error (S3010). When a constant's value depends on a condition, use an if expression, which gives a value when it has an else:

Sable
let limit = if isPremium { 100 } else { 10 }

Destructuring#

A let or var can take a value apart as it binds it. A tuple (see Tuples) binds element by element:

Sable
let pair = (3, "three")let (number, word) = pairprint("\(number) is \(word)")
3 is three

A struct binds field by field, by name, with braces. Write field: name to bind a field under another name:

Sable
struct Person {    var name: String    var age: Int}let person = Person { name: "Ada", age: 36 }let { name, age } = personlet { name: firstName } = personprint("\(name), \(age); \(firstName)")
Ada, 36; Ada

Naming Constants and Variables#

Names may contain almost any Unicode letter, digit or underscore, but can't start with a digit. Names are compared after Unicode normalisation (NFC), so two spellings of the same accented letter are the same name.

Sable
let π = 3.14159let 你好 = "你好世界"let maxRetries = 3

A single _ is not a name: it is the wildcard, which matches a value and throws it away, as in let (x, _) = point. A leading underscore otherwise has no special meaning.

To use a keyword as a name, put it in backticks. Do this only when there is no better name, such as when matching a name from another system:

Sable
let `class` = "first"print(`class`)

A name can't be declared twice in the same scope, but an inner scope may shadow a name from an outer one:

Sable
let level = 1if level > 0 {    let level = "inner"   // a new constant, hiding the outer one in this block    print(level)}print(level)
inner1

Declaring level a second time directly beside the first would be an error (S2000).

Printing Values#

print writes a value and a line break to standard output. It takes one value of any type: numbers, strings and Booleans print as text, and arrays, dictionaries, tuples and other values print as an interpolation would show them. To print several values, put them in a string with interpolation, writing each inside \( ):

Sable
let friendlyWelcome = "Bonjour!"print(friendlyWelcome)print("The current value of friendlyWelcome is \(friendlyWelcome)")print([1, 2, 3])
Bonjour!The current value of friendlyWelcome is Bonjour![1, 2, 3]

Strings and Characters covers interpolation and its format specs.

Comments#

Comments are text the compiler ignores. A line comment starts with //; a block comment starts with /* and ends with */:

Sable
// This is a comment./* This is also a comment   but is written over multiple lines. */

Block comments nest, so you can comment out a block of code that already contains a block comment:

Sable
/* This is the start of the first comment.    /* This is the second, nested comment. */   This is the end of the first comment. */

An unterminated block comment is reported where it opens, not at the end of the file.

Three more forms are documentation comments, which sable doc turns into documentation: /// documents the declaration after it, /** ... */ is its block form, and //! at the top of a file documents the module. Documentation comments are Markdown, and the code examples in them are compiled and run as tests. See Documentation and Testing.

Sable
/// The number of seconds in one day.let secondsPerDay = 86_400

Semicolons and Newlines#

Sable doesn't need semicolons. A newline ends a statement, unless the line so far can't be a complete statement. That means you can break a long expression over several lines, as long as each line ends with something that obviously wants more, such as an operator, a comma or an opening bracket, or the next line starts with something that obviously continues, such as . or a binary operator:

Sable
let total = 1 +    2 +    3let name = "ada"    .uppercased()
6ADA

The full rule is in Lexical Structure. Three parts of it are worth knowing now:

  • return, break, continue, throw and fallthrough always end at the newline. A returned value must be on the same line as return. This avoids the trap in JavaScript where a value on the next line is silently dropped.
  • An opening brace goes on the same line as what it belongs to. A { that starts a line is an error (S1011), because it would be ambiguous with a trailing closure. Sable takes Go's rule here, not Swift's.
  • >, >> and ? can end a statement, so that var xs: List<Int> and var x: Int? end where you expect. The price is that a multi-line expression can't break after one of them; put such an expression in parentheses instead.

Write a semicolon only to put several statements on one line. sable fmt removes ones that aren't needed.

Integers#

Integers are whole numbers, signed or unsigned. Sable has them in 8, 16, 32, 64 and 128 bits:

Signed Unsigned Bits
I8 U8 8
I16 U16 16
I32 U32 32
I64 U64 64
I128 U128 128
Int UInt the platform's word: 64 on a 64-bit machine

Each integer type has a min and a max:

Sable
print(U8.max)print(I32.min)print(Int.max)
255-21474836489223372036854775807

Use Int unless you have a reason not to: it is the type an integer literal gets when nothing says otherwise, it is what counts and indices are, and using one type throughout saves conversions. Reach for a fixed width when the size matters: a file format, a network protocol, a large array of small values, or C interop.

Arithmetic that overflows an integer type stops the program rather than wrapping silently. Basic Operators shows the operators that wrap on purpose.

Floating-Point Numbers#

Floating-point numbers have a fractional part, such as 3.14159 or -273.15. Sable has four IEEE 754 types:

Type Bits Use
F64 64 The default: about 15 decimal digits of precision
F32 32 About 6 decimal digits; half the memory, and what graphics code uses
F16 16 Half precision, for storage and some GPU work
BF16 16 bfloat16: an F32's range with only 8 bits of precision, used in machine learning

A floating-point literal is an F64 unless its context asks for another type. The types have constants such as F64.pi, F64.infinity and F64.nan, and division by zero gives an infinity rather than stopping the program:

Sable
print(F64.pi)print(1.0 / 0.0)print(0.1 + 0.2)
3.141592653589793inf0.30000000000000004

A float prints in the shortest digits that read back as the same value, which is why 0.1 + 0.2 shows its rounding error.

Type Safety and Type Inference#

Because Sable is type-safe, passing an Int where a String is wanted is a compile-time error, not a surprise at run time. Type inference keeps that from being a burden. When you declare a constant or variable with an initial value, its type is the value's type:

Sable
let meaningOfLife = 42        // Intlet pi = 3.14159              // F64let anotherPi = 3 + 0.14159   // F64

A literal has no type of its own: it takes the one its context asks for. In anotherPi, the 3 becomes an F64 because the other operand is one. With no context at all, an integer literal is an Int and a floating-point literal is an F64.

The same goes for an expression made only of literals: let mask: U16 = 1 << 12 computes in U16. An array literal's elements take the element type their context asks for, or else the type of the other elements:

Sable
let version: U8 = 3let header = [0x54, 0x5A, version]   // U8[]: the literals take version's type

Inference has limits, on purpose. A function's parameter and result types, a stored property's type, and anything public are always written out, which keeps errors local and module interfaces stable. A module-level constant may leave its type out only when its value is a literal, an array of literals, or a call of a type's initialiser (S2001).

Numeric Literals#

Integer literals can be written in four bases:

Sable
let decimalInteger = 17let binaryInteger = 0b10001       // 17 in binarylet octalInteger = 0o21           // 17 in octallet hexadecimalInteger = 0x11     // 17 in hexadecimal

Floating-point literals are decimal, with an optional exponent after e, or hexadecimal, with an exponent after p that is a power of two:

Sable
let small = 1.25e-2      // 0.0125let exponent = 1e-9let hex = 0x1.8p3        // 1.5 × 2³ = 12.0

A floating-point literal needs a digit on both sides of the point: 1. and .5 are not literals. That keeps 1..<5 and tuple.0 unambiguous.

Underscores may separate digits to make long numbers easier to read, anywhere but at the start:

Sable
let oneMillion = 1_000_000let mask = 0b1111_0000let justOverOneMillion = 1_000_000.000_000_1

Sable has no literal suffixes such as 5u8; that is an error (S0015). Give the type with an annotation, or with as. A literal that doesn't fit the type it is given is a compile-time error, never a wrap:

Sable
let tooBig: U8 = 300
error[S3200]: '300' does not fit in 'U8', which holds 0 through 255

Numeric Type Conversion#

Sable never converts one numeric type to another implicitly, not even when the conversion would be safe. Mixing types is an error until you say which you want:

Sable
let small: I32 = 5let wide: I64 = small     // error[S3004]: expected 'I64' but found 'I32'

Convert a value with as:

Sable
let twoThousand: U16 = 2_000let one: U8 = 1let twoThousandAndOne = twoThousand + (one as U16)

as is checked: a value that doesn't fit the target type stops the program, saying so. Converting a float to an integer drops its fractional part, and stops the program if the whole part doesn't fit:

Sable
let reading = 300let byte = reading as U8
fatal error: Int does not fit in U8
Sable
let three = 3let pointOneFourOneFiveNine = 0.14159let pi = (three as F64) + pointOneFourOneFiveNinelet integerPi = pi as Int    // 3

When you want the bits to wrap rather than trap, write unchecked as. It never stops the program: an integer keeps its low bits, and a float rounds toward zero and stops at the target's bounds, with NaN becoming 0:

Sable
print(reading unchecked as U8)      // 300 keeps its low 8 bits: 44print((-3.9) unchecked as U8)       // clamped to the bottom of U8's range: 0
440

Note

as binds tighter than a prefix minus, so -3.9 unchecked as U8 means -(3.9 unchecked as U8), which negates a U8 and overflows. Parenthesise a negative operand.

Numeric types also have initialisers that convert, F64(count) or U64(line.quantity); they convert the same way as does.

Why so strict? Implicit conversions are where silent truncation and sign bugs come from, and Sable would rather you see every place a value changes type. It is also why a conversion between types that could never be converted, such as two unrelated classes, is an error (S3066) rather than a cast that always fails.

Type Aliases#

A type alias gives an existing type another name. Declare one with alias:

Sable
alias AudioSample = U16var maxAmplitudeFound = AudioSample.maxprint(maxAmplitudeFound)
65535

An alias is the same type as what it names, not a new one: an AudioSample is a U16 wherever it is used. Aliases are most useful for naming a long type once:

Sable
alias Handler = async (Request) throws(HttpError) -> Responsealias Matrix = F64[4][4]

An alias may be generic, and may fill in some of another generic type's parameters:

Sable
alias Id<T> = U64public alias Result<T> = Outcome<T, AppError>

Sable spells this alias, not Swift's typealias; writing typealias is an error that tells you so (S1012).

Booleans#

Sable's Boolean type is Bool, and its two values are true and false:

Sable
let orangesAreOrange = truelet turnipsAreDelicious = false

Conditions in if, while and guard must be Bool. Unlike C, an integer is not a condition: if count { } is an error, and you write if count != 0 { }.

Sable
if turnipsAreDelicious {    print("Mmm, tasty turnips!")} else {    print("Eww, turnips are horrible.")}
Eww, turnips are horrible.

Tuples#

A tuple groups several values into one compound value. The values can be of any types, and needn't match:

Sable
let http404Error = (404, "Not Found")

This tuple's type is (Int, String). Read its elements by position, starting at zero, or take it apart with a let:

Sable
print("The status code is \(http404Error.0)")let (statusCode, statusMessage) = http404Errorprint("The status message is \(statusMessage)")let (justTheStatusCode, _) = http404Error
The status code is 404The status message is Not Found

Elements can be named, and a named element can be read by its name as well as its position:

Sable
let http200Status = (statusCode: 200, description: "OK")print(http200Status.statusCode)print(http200Status.1)print(http200Status)
200OK(statusCode: 200, description: "OK")

Tuples are most useful as a function's result, to return several values without declaring a type for them:

Sable
fn divmod(a: Int, b: Int) -> (q: Int, r: Int) {    return (q: a / b, r: a % b)}

Two tuples whose elements are all equatable compare with ==. For data that outlives a single expression or call, a struct is usually the better choice; see Structures and Classes.

Optionals#

An optional is a value that may be missing. Write it as the type followed by ?: an Int? holds either an Int or nothing at all, written none.

Sable
var serverResponseCode: Int? = 404serverResponseCode = none

A type without ? can never be none. That is the whole of Sable's answer to null: there are no null references, and no warnings-only mode like C#'s nullable reference types.

Unlike Swift, an optional variable has no implicit starting value. var answer: String? is unassigned, like any other declaration without a value, and reading it before assigning it is an error. Write = none when that is what you mean.

Optional Binding#

Use if let to find out whether an optional holds a value and, if it does, to bind that value to a new constant for the body of the if:

Sable
let timeout: Int? = 30if let seconds = timeout {    print("timing out after \(seconds)s")} else {    print("no timeout")}
timing out after 30s

Inside the body, seconds is an Int, not an Int?. When the new name would be the same as the optional's, you can leave out the = and the value:

Sable
if let timeout {    print("timing out after \(timeout)s")}

guard let binds the value for the rest of the scope instead, and leaves the scope when there is none; Control Flow covers it.

Defaults and Force-Unwrapping#

?? gives the optional's value, or a default when it is none:

Sable
let nickname: String? = noneprint(nickname ?? "anonymous")
anonymous

A postfix ! force-unwraps an optional: it gives the value, and stops the program if there is none. Use it only when you know a value is there:

Sable
let missing: Int? = noneprint(missing!)
fatal error: unwrapped a none

Optional<T> is an ordinary union with the cases Some(T) and None, and none is the idiomatic way to write .None. Optionals covers chaining with ?., narrowing and the rest.

Error Handling#

Optionals say a value may be missing. When you also need to say why, a function throws an error. Its declaration says what it may throw, throws(E), and every call to it is marked with try:

Sable
union PortError {    Empty    NotANumber(text: String)}fn parsePort(_ text: String) throws(PortError) -> Int {    guard !text.isEmpty else { throw .Empty }    guard let port = try? Int.parse(text) else { throw .NotANumber(text: text) }    return port}

A do block runs code that may throw, and its catch clauses handle the errors, by case:

Sable
do {    let port = try parsePort("eighty")    print("listening on \(port)")} catch .Empty {    print("no port given")} catch .NotANumber(let text) {    print("'\(text)' is not a number")}
'eighty' is not a number

There are three shorter forms of try:

Form When the call throws
try? f() The result is none, so try? f() is an optional
try f() catch { fallback } The fallback's value is used instead
try! f() The program stops: use it only when the call cannot fail
Sable
let maybe = try? parsePort("x")             // nonelet fallback = try parsePort("") catch { 80 }   // 80let port = try! parsePort("8080")           // 8080

A function that doesn't handle an error can pass it on to its own caller, by being declared throws too. Errors are typed and checked: the compiler knows exactly what each call can throw, and a do that doesn't handle every case is an error. They are also cheap, compiled to an ordinary return value rather than to exception unwinding. Error Handling has the details.

Assertions and Preconditions#

Some conditions must hold for a program to go on at all. When one doesn't, there is no error to handle: the program has a bug, and the safest thing is to stop. Sable has a family of functions for this. Each stops the program with a message and the file, line and column it was called from. None can be caught.

precondition checks a condition in every build. Use it for what a function demands of its caller:

Sable
fn average(_ values: Int[]) -> Int {    precondition(values.count > 0, "average of no values")    var sum = 0    for v in values {        sum += v    }    return sum / values.count}
fatal error: precondition failed: average of no values  at average.sb:4:5

assert checks only in a debug build, where DEBUG is defined: an unoptimised build, or a profile with debug-assertions on. Use it for checks of your own reasoning, which a release build can trust. In a release build nothing in an assert call runs at all, neither the condition nor the message, because both are taken as autoclosures:

Sable
fn half(_ n: Int) -> Int {    assert(n % 2 == 0, "only even numbers are halved, not \(n)")    return n / 2}

Note

sable run file.sb builds a single file optimised by default, so its asserts are off. Run it with -O0 to check them. A package's sable run uses the dev profile, where they are on.

The rest give up unconditionally. Each returns Never, so it can stand where any value is wanted, such as the last line of a function that must return something:

Function Says Use it for
fatalError("…") fatal error and the message A state the program can't recover from
preconditionFailure("…") precondition failed: … The failing branch of a check too complex for one condition
todo("…") not yet implemented: … Code you haven't written yet, like Rust's todo!
unreachable("…") reached code marked unreachable(): … A branch that can never run

assertionFailure("…") is the debug-only counterpart of preconditionFailure. The message is optional for all of them.

Sable
fn sign(_ n: Int) -> String {    if n < 0 { return "-" }    if n > 0 { return "+" }    if n == 0 { return "0" }    unreachable("every Int is negative, positive or zero")}

The language itself stops a program the same way on an integer overflow, a division by zero, an index out of range, or a force-unwrapped none. Panics like these are kept apart from errors on purpose: an error is something a caller can reasonably handle; a panic is a bug.

Module-Level Values#

Constants and variables can also be declared at the top level of a module, outside any function. There are three kinds:

Sable
let defaultPort = 8080                  // a module-level constantvar requestsServed = 0                  // a module-level variablestatic let MaxUsers = 10_000            // set once, as the program startsconst Pi: F64 = 3.14159265358979        // computed at compile time, inlined

A const is worked out while the program compiles, and written as a literal wherever it is read. Its value can call const fns, which run in the compiler's interpreter:

Sable
const fn square(_ n: Int) -> Int => n * nconst Area = square(12)

A trap while computing a constant, such as an overflow, is a compile-time error. Compile-Time Evaluation covers const fully.

Initialisation Order#

Module-level lets and vars, and types' static stored properties, get their initial values once, on one thread, before main begins (or, in a library, before its first function runs). After that, reading one costs nothing but the read: there is no lazy check on each access, as there is for a Swift global.

The order is worked out for you. A value is set after every value its initial value reads, directly or through the functions it calls; otherwise values are set in the order they are written, the standard library's first. So this works, even though Greeting is written before the Name it reads:

Sable
static let Greeting: String = makeGreeting()static let Name = "Sable"fn makeGreeting() -> String => "hello, \(Name)"
hello, Sable

Two values that need each other can't both be set first, and that is a compile-time error:

Sable
static let A: Int = B + 1static let B: Int = A + 1
error[S3411]: the initial values of 'A' and 'B' need each other, so none can be set first: 'A' reads 'B' and 'B' reads 'A'

When a value should instead be computed the first time it is asked for, give a type a lazy property; see Properties.

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.