Contents Open

DocsLanguage Guide

Basic Operators

Arithmetic, overflow and wrapping, comparison, logic, ranges, and how operators bind.

An operator is a symbol or short word that checks, changes or combines values. You already know most of Sable's from C, C# or Swift: + adds two numbers, && combines two Booleans, a < b compares. A few behave differently than in C on purpose. Arithmetic that overflows stops the program instead of wrapping, assignment can't be confused with a comparison, and there is a separate set of operators for when you do want wrapping arithmetic.

This chapter covers the operators built into the language. Methods, Subscripts and Operators shows how to give your own types operators such as + and ==.

Terminology#

Operators are unary, binary or ternary:

  • A unary operator works on one value. Prefix operators come before it (-a, !done), and postfix operators after it (value!).
  • A binary operator works on two values and sits between them (2 + 3).
  • The ternary operator works on three. Sable has one, the conditional operator a ? b : c.

The values an operator works on are its operands. In 1 + 2, the + is a binary operator and its operands are 1 and 2.

Assignment Operator#

The assignment operator, a = b, sets the value of a to the value of b:

Sable
let b = 10var a = 5a = b// a is now 10

When the right side is a tuple, a let or var can take it apart into several names at once:

Sable
let (x, y) = (1, 2)// x is 1, and y is 2

Assignment binds most loosely of all the operators, and groups to the right, so a = b = 0 sets b and then a.

What you assign to must be a place that can be written: a var, a property with a setter, an element of a variable array. Assigning to a let is an error (S3010).

Arithmetic Operators#

Sable has the four standard arithmetic operators for every numeric type:

Sable
print(1 + 2)print(5 - 3)print(2 * 3)print(10.0 / 2.5)
3264.0

Both operands of an arithmetic operator have the same type, since Sable never converts between numeric types implicitly. Mixing an Int and an F64 is an error until you convert one with as (The Basics). Literals are the exception that proves the rule: a literal takes its type from the other operand, so ratio * 2 works whether ratio is an F32 or an F64.

Integer division rounds toward zero:

Sable
print(7 / 2)print(-7 / 2)
3-3

+ also joins strings:

Sable
print("hello, " + "world")
hello, world

Overflow Traps#

An integer operation whose result doesn't fit its type is not silently wrapped. It stops the program:

Sable
var level: U8 = 200level += 100
fatal error: integer overflow  at levels.sb:5:5

The same goes for dividing an integer by zero, which stops with division by zero, and for shifting by a count outside the type's width, which stops with shift out of range. Floating-point arithmetic follows IEEE 754 instead: 1.0 / 0.0 is infinity, and nothing traps.

These checks are on in every build, release builds included. A package can turn them off with the overflow-checks setting of a build profile, in which case +, -, *, negation and as wrap. That is a decision for the whole build; within code, the operators in the next section say exactly where wrapping is wanted.

Overflow Operators#

When you want an integer to wrap, use a wrapping operator: &+, &- and &*. Each keeps the low bits of the result, and never traps:

Sable
let big: U8 = 250print(big &+ 10)print(I8.max &+ 1)print(Int.min &- 1)
4-1289223372036854775807

They bind as their ordinary counterparts do (&* like *, &+ and &- like +), and have compound forms, &+=, &-= and &*=. They are the natural tools for hashes, checksums and random number generators:

Sable
var hash: U32 = 2_166_136_261for byte in "sable".utf8 {    hash ^= byte as U32    hash &*= 16_777_619}

The wrapping operators belong to every fixed-width integer, as do the methods wrappingAdd, wrappingSub and wrappingMul, which do the same thing.

Note

& followed directly by +, - or * is always read as a wrapping operator. To bitwise-and with a negated value, put a space after the &: x & -x, not x&-x.

Remainder Operator#

The remainder operator, a % b, gives what is left over after dividing a by b as many whole times as will fit:

Sable
print(9 % 4)print(-9 % 4)print(9 % -4)
1-11

The result takes the sign of the left operand, a; the sign of b doesn't matter. This is a remainder, as in C and Swift, rather than a modulo, which always has the sign of the divisor.

% works on floating-point numbers too:

Sable
print(9.5 % 2.0)print(-9.5 % 4.0)
1.5-1.5

Unary Minus and Plus#

A prefix - flips the sign of a number. A prefix + gives the value unchanged, and can make code with negative numbers read more evenly:

Sable
let three = 3let minusThree = -threelet plusThree = -minusThreelet alsoMinusSix = +(-6)

Negating the most negative value of a signed type overflows, since its positive counterpart doesn't fit, and so traps like any other overflow.

Compound Assignment Operators#

A compound assignment operator combines an operation with assignment:

Sable
var a = 1a += 2// a is now 3

Every binary arithmetic and bitwise operator has one: +=, -=, *=, /=, %=, &=, |=, ^=, <<= and >>=, the wrapping &+=, &-= and &*=, and ??= (see Nil-Coalescing Operator). You don't declare them: each comes from its binary operator, including on your own types.

A compound assignment works out what its target is once, before it evaluates the right side. Here next runs once, the element is read, 5 is added, and the sum is stored back where it was read:

Sable
fn next(_ counter: inout Int) -> Int {    counter += 1    print("next called")    return counter}var scores: Int[>..] = [10, 20, 30]var position = -1scores[next(&position)] += 5print(scores)
next called[15, 20, 30]

Comparison Operators#

Sable supports the standard comparison operators. Each gives a Bool:

Operator Meaning
a == b Equal to
a != b Not equal to
a > b Greater than
a < b Less than
a >= b Greater than or equal to
a <= b Less than or equal to
Sable
print(1 == 1)print(2 != 1)print(2 > 1)print(1 < 2)print(1 >= 1)print(2 <= 1)print("apple" < "banana")
truetruetruetruetruefalsetrue

Comparison operators are most often used in conditions:

Sable
let name = "world"if name == "world" {    print("hello, world")} else {    print("I'm sorry \(name), but I don't recognize you")}

A type can be compared with == when it is Equatable, and ordered with < when it is Comparable. The built-in numbers, strings and characters are both. So is every kind of array whose elements are: arrays compare element by element, and order lexicographically. Two tuples compare with == and != when their elements are equatable, but tuples have no ordering. Your own types gain the operators by conforming to the protocols, often by having the compiler derive them; see Derivation and Source Generators.

Identity Operators#

Classes are reference types, so two constants can refer to the same object. === asks whether they do, and !== whether they don't:

Sable
class Player {    var name: String    init(name: String) { self.name = name }}let first = Player(name: "Ann")let second = Player(name: "Ann")let same = firstprint(first === same)print(first === second)print(first !== second)
truefalsetrue

first and second might be equal by some measure, but they are two objects. Identity only means something for classes: === on two structs is an error (S3009), because a value has no identity of its own.

Ternary Conditional Operator#

The ternary conditional operator, question ? answer1 : answer2, gives answer1 when question is true and answer2 when it is false. Only the chosen answer is evaluated.

Sable
let contentHeight = 40let hasHeader = truelet rowHeight = contentHeight + (hasHeader ? 50 : 20)print(rowHeight)
90

It is shorthand for an if that gives a value. For anything longer than one short line, the if expression usually reads better:

Sable
let rowHeight2 = contentHeight + (if hasHeader { 50 } else { 20 })

Nil-Coalescing Operator#

The nil-coalescing operator, a ?? b, gives the value inside the optional a if there is one, or b if a is none. b is evaluated only when it is needed:

Sable
let defaultColorName = "red"var userDefinedColorName: String? = nonevar colorNameToUse = userDefinedColorName ?? defaultColorNameprint(colorNameToUse)userDefinedColorName = "green"colorNameToUse = userDefinedColorName ?? defaultColorNameprint(colorNameToUse)
redgreen

When b is not optional, the result isn't either. When b is also optional, the result is optional, and ?? chains to try several in turn:

Sable
let fromFlag: String? = nonelet fromEnvironment: String? = noneprint(fromFlag ?? fromEnvironment ?? "default")
default

Because throw is an expression, the right side can give up instead of giving a value:

Sable
let port = configured ?? throw ConfigError.Missing(key: "port")

a ??= b assigns b to a only when a is none, which suits a cache:

Sable
var cached: Int? = nonecached ??= 42cached ??= 7print(cached!)
42

Optionals covers the rest of the optional operators: ?. for chaining and ! for force-unwrapping.

Range Operators#

Sable has operators that make ranges of values.

Closed Range Operator#

The closed range operator, a...b, makes a range from a to b, including both:

Sable
for index in 1...3 {    print("\(index) times 5 is \(index * 5)")}
1 times 5 is 52 times 5 is 103 times 5 is 15

Half-Open Range Operator#

The half-open range operator, a..<b, makes a range from a up to but not including b. It suits counting through an array, which starts at index zero:

Sable
let names = ["Anna", "Alex", "Brian", "Jack"]for i in 0..<names.count {    print("Person \(i + 1) is called \(names[i])")}
Person 1 is called AnnaPerson 2 is called AlexPerson 3 is called BrianPerson 4 is called Jack

One-Sided Ranges#

A range can leave out one bound, and then goes on as far as it can in that direction: 2... from index 2 to the end, ...2 from the start through index 2, ..<2 from the start up to index 2:

Sable
for name in names[2...] {    print(name)}for name in names[..<2] {    print(name)}
BrianJackAnnaAlex

A one-sided range is also a value of its own, which can say whether it contains something:

Sable
let range = ...5print(range.contains(7))print(range.contains(-1))
falsetrue

Sable has no range with neither bound (Swift's xs[...]): the whole of a collection is just the collection.

Counting From the End#

A prefix ^ counts a position back from a collection's end, as in C#: ^1 is the last element, ^2 the one before it, and ^0 the end itself. It binds tighter than every binary operator, so it can be a bound of a range without parentheses:

Sable
print(names[^1])print(names[^2...])print(names[1..<^1])
Jack["Brian", "Jack"]["Alex", "Brian"]

A position from the end that falls outside the collection traps, rather than counting from the other end as a negative index would in Python. Prefix ^ means nothing else: a ^ b is still exclusive or. Arrays and Collections covers slicing, writing through ranges, and ranges as values.

Logical Operators#

The logical operators combine Boolean values:

  • NOT, !a, gives the opposite of a.
  • AND, a && b, is true only when both are.
  • OR, a || b, is true when either is.
Sable
let allowedEntry = falseif !allowedEntry {    print("ACCESS DENIED")}
ACCESS DENIED

&& and || short-circuit: && doesn't evaluate its right side when the left is false, and || doesn't when the left is true. That lets the left side guard the right, as in index < items.count && items[index] > 0.

Sable
fn check(_ value: Bool, _ name: String) -> Bool {    print("checked \(name)")    return value}if check(false, "left") && check(true, "right") {    print("both")}
checked left

You can combine several logical operators. && binds tighter than ||, so this reads as "either the code and the scan, or the key, or the password":

Sable
let enteredDoorCode = truelet passedRetinaScan = falselet hasDoorKey = falselet knowsOverridePassword = trueif enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {    print("Welcome!")} else {    print("ACCESS DENIED")}
Welcome!

Parentheses make the intent explicit, and cost nothing: (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword.

Bitwise Operators#

The bitwise operators work on the individual bits of an integer:

Operator Name Result
~a NOT Every bit flipped
a & b AND Bits set in both
a | b OR Bits set in either
a ^ b XOR Bits set in one but not the other
a << n Left shift Bits moved n places left, zeros coming in
a >> n Right shift Bits moved n places right
Sable
let bits: U8 = 0b1111_0000print(~bits)print(bits & 0b1010_1010)print(bits | 0b0000_0011)print(bits ^ 0b1111_1111)print(bits >> 4)
151602431515

Bits shifted past the end of the type are discarded. A right shift of a signed integer keeps its sign, filling with copies of the sign bit:

Sable
let negative: I8 = -16print(negative >> 2)
-4

A shift by a count less than zero, or not less than the type's width, traps (shift out of range).

@flags enums use |, &, ^ and ~ to combine their flags; see Enums and Unions.

Other Operators#

A few more prefix operators appear throughout the guide:

  • &x marks an argument the call may change, for an inout parameter, or makes a reference to a place. See Functions and Memory and Ownership.
  • try and await mark a call that may throw or suspend. See Error Handling and Concurrency.
  • move x moves a value out of a variable, leaving the variable empty until it is assigned again. Any value can be moved this way; a @noncopy value moves whenever it is used. Reading the variable afterwards is an error (S3057):
Sable
let text = "draft"let published = move textprint(published)print(text)
error[S3057]: 'text' is used after its value was moved out of it, at line 2

There are also postfix and binary operators for types: ! to force-unwrap an optional, ?. to chain through one, and as, as?, as! and is to convert and test types, covered in Optionals and Casting, Metatypes and Reflection.

Discarding a Result#

A function's result is meant to be used. Calling one and ignoring what it gives is reported by the unused_result lint (S3308):

Sable
fn double(_ n: Int) -> Int => n * 2double(4)
warning[S3308]: the result of 'double' is unused; write '_ = ...' if that is meant, or mark 'double' '@discardable' [unused_result]

To drop a result on purpose, assign it to _:

Sable
_ = double(5)

The value is made and then destroyed, and the statement gives nothing. _ is only an expression in this position. A function whose result is often not needed, such as one that returns a value for chaining, can be marked @discardable instead.

Operator Precedence#

When an expression has several operators, precedence decides which apply first. Multiplication binds tighter than addition, so 1 + 2 * 3 is 1 + (2 * 3), which is 7. Sable's precedence is fixed by the grammar, and these are its levels, from the tightest-binding to the loosest:

Level Operators
1 a.b a?.b a! a[i] f(x) a as T a is T Postfix, member access, casts
2 -a !a ~a &a ^a await a try a move a Prefix
3 * / % &* Multiplicative
4 + - &+ &- Additive
5 << >> Shifts
6 ..< ... Ranges
7 < <= > >= Ordering
8 == != === !== Equality
9 & Bitwise AND
10 ^ Bitwise XOR
11 | Bitwise OR
12 && Logical AND
13 || Logical OR
14 ?? Nil-coalescing
15 ? : Ternary conditional
16 = += and every compound assignment Assignment, grouping to the right

A few consequences are worth knowing, because they differ from Swift or C:

  • Casts bind tighter than prefix operators. -x as I8 is -(x as I8). Parenthesise a negated operand: (-x) as I8.
  • Shifts bind more loosely than arithmetic, as in C: 1 << 2 + 1 is 1 << 3, which is 8. In Swift it would be 5.
  • Bitwise &, ^ and | bind more loosely than comparison, also as in C. flags & 1 == 1 means flags & (1 == 1), which is an error because 1 == 1 is a Bool. Write (flags & 1) == 1.
Sable
let flags = 5print((flags & 1) == 1)print(1 << 2 + 1)
true8

When in doubt, add parentheses. sable fmt keeps them.

Operators on Your Own Types#

You can give your own types most of these operators: + - * / % & | ^ << >> == != < <= > >= [] () and prefix - ! ~. Declaring a binary operator gives you its compound assignment for free.

Some operators can't be overloaded, because their meaning is part of the language: &&, ||, ??, ?., =, ., as and is. Nor can you invent new operators. Sable has no custom operators, so every operator in a program is one from the table above, with the precedence it shows. Methods, Subscripts and Operators shows how to declare them.

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.