DocsLanguage Reference
Types
Every built-in type and every form of type syntax, and how types relate.
Sable is nominally typed: two structs with identical fields are different types. A type is either named — a built-in type, a struct, class, actor, union, enum or protocol, an alias — or compound, written with type syntax out of other types: optionals, references, arrays, dictionaries, tuples, functions, structural unions, existentials and metatypes. This chapter lists every built-in type and every form of type syntax, then states how types relate (subtyping) and which types the compiler infers.
The guide introduces these types one at a time: the built-in types in The Basics, arrays and dictionaries in Arrays and Collections, optionals in Optionals, some and any in Protocols, references in Memory and Ownership, and metatypes in Casting, Metatypes and Reflection.
Built-in types#
| Type | Description |
|---|---|
Bool |
true or false |
I8 I16 I32 I64 I128 |
Signed integers of 8 to 128 bits |
U8 U16 U32 U64 U128 |
Unsigned integers of 8 to 128 bits |
Int UInt |
The platform's word size; Int is the default type of an integer literal |
F16 F32 F64 |
IEEE 754 binary16, binary32, binary64; F64 is the default type of a float literal |
BF16 |
bfloat16: an F32's range at 8 bits of precision |
Char |
One Unicode scalar value |
String |
UTF-8 text, growable; a range of one, text[a..<b], is a Substring |
Void |
The unit type, with one value; written () in type position |
Never |
The empty type, with no values; a function returning Never does not return |
Type |
Any type, known at run time, as a value (the existential metatype) |
GenericType |
A generic type without its arguments, as a value |
Numeric types never convert implicitly: widening an I32 to an I64 is written x as I64. Optional<T> and the array, dictionary and range types are library types with syntax of their own, below.
Type syntax#
Type = UnionType ;UnionType = IntersectionType { "|" IntersectionType } ; (* structural union *)IntersectionType = PostfixType { "&" PostfixType } ; (* composition *)PostfixType = PrimaryType { TypeSuffix } ;TypeSuffix = "?" (* optional *) | "!" (* iuo *) | "&" [ "<" RelRefSpec ">" ] [ "?" ] (* reference *) | ArraySuffix | "." Identifier [ GenericArgs ] ; (* nested / associated *)PrimaryType = QualifiedName [ GenericArgs ] | "some" Type | "any" Type | "~" Type (* "~Copyable", as a constraint only *) | TupleType | FunctionType | "(" Type ")" | "Self" ;Every form at a glance:
| Syntax | Meaning |
|---|---|
T? |
Optional |
T! |
Implicitly unwrapped optional (interop only, discouraged) |
T& |
Reference: a machine address |
T&<u32> |
Relative reference: a 4-byte offset from the field |
T&<u16 in pool> |
Relative reference from a named pool base |
T&? |
Optional reference |
T[] |
Array, fixed at construction |
T[8] |
Fixed size, its elements inline |
T[..], T[..64] |
Inline capacity, resizable within it, its elements inline |
T[>..] |
Grow-only array |
T[>..<] |
Grow/shrink array |
T[:] |
Slice view |
[K: V] |
Dictionary |
(A, B, C) |
Tuple |
(label: A, b: B) |
Labelled tuple |
(A, B) -> C |
Function type |
(A) throws(E) -> C |
Throwing function type |
async (A) -> C |
Async function type |
(inout A) -> () |
Function that changes its argument in place |
A | B | C |
Structural union |
some P |
Opaque type conforming to P |
any P |
Existential box conforming to P |
any Any |
A value of any type |
T.Type |
The metatype of T |
any P.Type |
A type that conforms to P |
P & Q |
Protocol composition |
Foo<T, U> |
Generic instantiation |
Outer.Inner, S.Element |
Nested or associated type |
Self |
The enclosing type |
~Copyable |
Suppresses the implicit Copyable constraint (constraints only) |
Suffixes apply left to right, so Int?[] is an array of optionals and Int[]? an optional array. some and any take the whole type after them, so an array of existentials needs parentheses: (any Drawable)[].
Named types and generic arguments#
GenericArgs = "<" GenericArg { "," GenericArg } ">" ;GenericArg = Type | IntegerLiteral ; (* for a value parameter: Buf<Int, 4> *)A named type is a possibly qualified name, Shape or Geometry.Shape, with generic arguments if the type is generic. An argument is a type, or for a value parameter (a generic parameter constrained to an integer type, N: Int) an integer literal or the name of an integer constant:
struct Ring<T, N: Int> where N > 0 { var slots: T[N]}let ring = Ring<Int, 2> { slots: [1, 2] }const lanes = Platform.vectorBytes / 4let v: SIMD<F32, lanes> = SIMD(repeating: 1)Each instance of a value parameter is a type of its own. A constant used as an argument must be computable as the type is read — integer literals, other such constants and integer operators; one computed by a call is S3420. A false where predicate on a value parameter is S3421. An expression is never written in the angle brackets, where > would end them.
T.Name names a type nested in T, or an associated type of a type parameter: S.Element, S.Iter.Element.
Optional types#
T? is Optional<T>, a frozen union:
@frozen union Optional<T> { Some(T), None }none is Optional.None, valid only where an optional is expected; .Some(x) and .None are spellable too. A T converts to a T? implicitly wherever one is expected. A non-optional type never holds none: optionality is always in the type. With spare-bit packing, a T? of a class or a reference is a single pointer, none the null one.
T! is an implicitly unwrapped optional: an optional that is unwrapped, trapping on none, wherever it is used as a T. It exists for interop and is discouraged elsewhere.
The operators over optionals (?., ??, ??=, !) and binding (if let) are in Expressions and Statements.
Reference types#
RelRefSpec = ( "u8" | "u16" | "u32" | "i8" | "i16" | "i32" ) [ "in" Identifier ] ;T& is a reference to a T stored somewhere else: a machine address. It is the only way to write a reference type; ref T and borrowing T are reserved and refused (S1013). A reference is written:
- as a parameter's type,
fn area(_ r: Rect&) -> F64: the callee reads the caller's value in place; - as a result type,
-> Node&: the function returns a reference rooted in one of its parameters; - as a local's or field's type, holding what
&expror a call gives.
Whether a reference may be returned, and how long it may be used, is decided by root inference (Memory and Ownership): one that would outlive its root is an error (S3061), and using its root while it is in use is S3062. T&? is an optional reference.
Relative references store an offset rather than an address, for @inline_layout data that must stay pointer-free. T&<u32> is a 4-byte offset from the field that holds it; the width is one of u8, u16, u32, i8, i16, i32. T&<u16 in pool> is an offset from the base of a named pool. See Inline Layout.
public union Node.. { Leaf(value: I32) Branch(left: Node&<u32>, right: Node&<u32>)}Array types#
ArraySuffix = "[" "]" (* T[] *) | "[" Expression "]" (* T[k] *) | "[" ".." [ Expression ] "]" (* T[..] T[..k] *) | "[" ">" ".." "]" (* T[>..] *) | "[" ">" ".." "<" "]" (* T[>..<] *) | "[" ":" "]" (* T[:] *) | "[" Type ":" Type "]" ; (* [K: V] *)Sable has a family of array types, each a different contract about how its count may change:
| Type | Storage | Count |
|---|---|---|
T[] |
Heap buffer | Fixed when made |
T[k] |
Inline, where the array is | Exactly k |
T[..k] |
Inline, capacity k |
Grows within k; append past it traps |
T[>..] |
Heap buffer | Grows at its end only |
T[>..<] |
Heap buffer | Grows and shrinks at its end |
T[:] |
A view of another array's elements | Never changes |
Every kind can be viewed as a slice, so a member declared on T[:] is a member of every kind. An inline array's size is part of its type (Int[4] and Int[5] differ) and it takes at most 64 KiB (S7004). Every array is Equatable, Hashable and Comparable (lexicographically) when its element is. xs as Int[] converts a grown array to a fixed one and back, sharing elements until either changes. Inserting and removing in the middle is List<Element>'s (Sable.Collections), not an array's.
Array types compose: F64[4][4] is a fixed 4×4 matrix.
Dictionary types#
[K: V] is Dictionary<K, V>, whose key must be Hashable. A dictionary keeps its entries in insertion order. [:] is the empty dictionary, and [String: Int]() makes one by its type's init().
Tuple types#
TupleType = "(" [ TupleTypeElem { "," TupleTypeElem } ] ")" ;TupleTypeElem = [ Identifier ":" ] [ "inout" ] Type ; (* "inout": a function type's parameter only *)A tuple type lists its elements' types, optionally labelled: (Int, String), (q: Int, r: Int). Elements are read by label or position, pair.q, pair.0. () is Void. A parenthesised single type, (T), is just T. inout is allowed only on a function type's parameter.
Function types#
FunctionType = [ "async" ] TupleType [ ThrowsSpec ] "->" Type ;ThrowsSpec = "throws" [ "(" Type ")" ] | "rethrows" ;A function type is a parameter list in parentheses, its effects, and a result:
let compare: (Int, Int) -> Bool = { a, b in a < b }let parse: (String) throws(ParseError) -> Int = Int.parselet fetch: async (Url) throws -> Response = loadlet bump: (inout Int) -> () = { $0 += 1 }throws(E)says the function may throw anE; barethrowsmeansthrows(any Error). A function type never saysrethrows, which belongs to declarations.asyncbefore the parameter list makes the function async; it composes withthrows:async (A) throws(E) -> C.- An
inoutparameter is passed&xby the caller and changed in place. @escapingon a parameter's function type says the callee may keep the closure:(@escaping () -> Int) -> Void. It is part of the type. A function that keeps less fits where one that may keep more is wanted, not the reverse (S3004).
Structural union types#
A | B | C is a value of exactly one of the listed types. Structural unions are the one place Sable compares types structurally: two are the same type when their cases are the same after normalisation, which
- flattens nested unions,
(A | B) | CtoA | B | C; - removes duplicates;
- sorts the cases in a stable order;
- collapses subsumption:
Int | NeverisInt, andT | T?isT?.
alias Json = Bool | F64 | String | Json[] | [String: Json]fn render(_ v: Int | String) -> String { if v is Int { return v.toString() } // v is an Int here return v // and a String here}A structural union is bounded: every case is known at compile time, so it may not contain any P for a protocol open to new conformances. That is what makes matching on one checkable for exhaustiveness. A value of any case type converts to the union implicitly. is, match, if let and != none narrow a union-typed binding, flow-sensitively (see Type inference). It is lowered to a nominal tagged union, one per normalised case set.
Opaque and existential types#
some P and any P both describe "a type that conforms to P", in opposite ways.
some P is one concrete type that the compiler knows and the code using it does not. As a result type, the function picks the type and its callers rely only on P; two calls return the same type. As a parameter type, some P is a generic parameter: fn draw(_ d: some Drawable) is fn draw<D: Drawable>(_ d: D). It costs nothing at run time.
any P is a box that holds a value of any conforming type, decided as the program runs: heterogeneous collections, stored properties of protocol type. A requirement called through one is dispatched through the type's witness table; calling a requirement that takes Self or an associated type opens the existential where the result can be erased again (see Casting, Metatypes and Reflection).
fn makeShape() -> some Drawable { return Circle(radius: 1) }fn allShapes() -> (any Drawable)[] { return [Circle(radius: 1), Square(side: 2)] }A protocol's associated types may be given in angle brackets after the protocol's name, in the order it declares them: some Sequence<Int> is a sequence whose Element is Int, and some Sequence<Int, ParseError> one whose Failure is ParseError. An associated type left out takes its default.
any Any is a value of any type at all. An any Error is the type of a bare throws.
Protocol composition#
P & Q is a type conforming to both, used after some or any or as a constraint: some Hashable & Debug, alias Key = any Hashable & Equatable, <T: Encodable & Sendable>.
Metatypes#
T.Type is the type of T.self, the type T as a value. Its one value is T, known where the code is compiled; in generic code it is a constant of each instance. Any type has one, compound types included: Int?.Type, Int[>..].Type.
| Type | Values |
|---|---|
T.Type |
Exactly the type T |
Type |
Any type, known at run time |
any P.Type |
Any type that conforms to the non-generic protocol P |
GenericType |
A generic type without arguments, Stack.self |
Every T.Type converts to Type, and a conforming T.Type to any P.Type; nothing converts back implicitly (t as? any Zero.Type asks the conformance registry). A Type reaches no static member of the type it holds, and no cast is to one (S3098). Two metatypes compare with ==. The expressions that make and use metatypes are in Expressions.
Self#
Inside a type, its extensions and a protocol, Self is the enclosing type — in a protocol, the conforming type. Self(x: 3) and Self.zero use it in expressions.
Regions#
region is the type of a region parameter or a stored region: fn build(in r: region) -> Node& takes the region to allocate in (the in there is the parameter's label), and private let frameArena: region stores one. A reference into a region is rooted in it. See Memory and Ownership and the region statement in Statements.
Suppressed constraints#
TypeList = ConstraintType { "&" ConstraintType } ; (* composition in constraints *)ConstraintType = [ "~" ] Type ; (* "~Copyable" lifts the implicit constraint *)Every type parameter is implicitly Copyable. Writing ~Copyable in its constraints lifts that, so a generic type or function can hold move-only (@noncopy) values. It is allowed only as a constraint:
struct MoveHolder<T: ~Copyable> { var item: T}fn keep<T: ~Copyable>(_ x: consuming T) -> MoveHolder<T> { return MoveHolder { item: x }}Type aliases#
AliasDecl = "alias" Identifier [ GenericParams ] "=" Type NL ;alias gives a type another name. The alias and the type are the same type, interchangeable everywhere.
alias Handler = async (Request) throws(HttpError) -> Responsealias Matrix = F64[4][4]alias Id<T> = U64 // generic, T unused (a phantom)public alias Result<T> = Outcome<T, AppError> // partial application- An alias may be generic, and its parameters may be constrained. A parameter it does not use is a phantom:
Id<User>andId<Order>are bothU64. - Giving some of a generic type's arguments and leaving the rest as the alias's parameters is partial application.
- A generic alias named bare where an initialiser is called infers its parameters as a generic type would: for
alias GzipReader<R: Reader> = DecompressingReader<GzipDecoder, R>,GzipReader(file)withfile: FileHandleis aDecompressingReader<GzipDecoder, FileHandle>. - In a conforming type, an alias gives a protocol's
associatedtypeits type. Sable spells italias, nevertypealias(S1012).
Subtyping#
The subtyping relation is deliberately small. Where a type on the left is given, a type on the right is accepted, by an implicit conversion:
| Rule | Meaning |
|---|---|
T <: T? |
Optional promotion |
Derived <: Base |
Class inheritance |
Derived? <: Base? |
An optional of a subclass; none stays none |
T <: any P when T: P |
Existential erasure, which boxes |
T.Type <: Type |
Metatype erasure |
T <: A | B when T is A or B |
Union injection |
Never <: T |
Never is the bottom type |
(A) -> B <: (A') -> B' when A' <: A and B <: B' |
Function types: contravariant parameters, covariant result |
@noncopy T has no supertypes |
No subtyping for move-only types |
Notably absent:
- Numeric subtyping:
I32is not anI64; widening is an explicitas. - Structural record subtyping: a struct with more fields is not a struct with fewer.
- Array covariance and generic variance:
List<Dog>is not aList<Animal>. Generic types are invariant. Only a protocol may declare variance on its parameters —protocol Producer<out T>(covariant:Tin results only),protocol Consumer<in T>(contravariant:Tin parameters only) — which makes its existentials variant. A parameter used in the wrong position is S3047.
The one other implicit conversion in the language is between error types at a try, through a From conformance; see Error Handling.
Type inference#
Sable's checker is bidirectional: it infers types from expressions and pushes expected types into them. Its reach is deliberately limited, so that checking stays fast and errors stay local.
| Inferred | Not inferred |
|---|---|
Local let and var types, from the initialiser |
Function parameter types |
| Generic arguments at call sites | Function return types (except => bodies) |
| Closure parameter and return types, from context | Stored property types |
| Literal types, from context | Public API signatures |
| The union case of a leading-dot expression |
Public signatures are always written out in full. This keeps module interfaces stable and lets modules be checked in parallel.
Inference runs both ways:
- A generic call, initialiser or static member whose arguments do not settle its type parameters takes them from the type the context expects:
let z: Complex<F64> = Complex.i,let n: F64 = two()forfn two<T: Numeric>() -> T. - An operator's operands are each other's context. The right operand of
+,*,==and the other operators whose operands share a type is checked expecting the left's type, and a left operand only context can type (.zero,two()) takes the right's:Complex.i + z. Evaluation is still left to right. - A literal, or an expression of literals alone (
29 << 112,-(1 + 2)), takes the type its context asks for, and otherwise defaults toIntorF64. An array literal's literals take the element type the context asks for, or the type of its other elements:[0x54, 0x5A, version]withversion: U8is aU8array.
The solver has a hard step limit (10,000 by default). An expression that exceeds it is reported at the subexpression that used the budget, with a suggestion to add an annotation, rather than an "expression too complex" error.
Flow-sensitive narrowing#
A test narrows the type of a binding in the code it guards:
fn describe(_ x: Int | String | Bool) { if x is Int { print(x + 1) // x: Int } match x { case let s as String => print(s) // s: String case _ => print("other") }}is, match, if let, guard let and != none narrow. Narrowing is invalidated by an assignment to the binding, or by a call that could change it (a var captured by reference).