Contents Open

DocsLanguage Reference

Declarations

Every declaration and every modifier that may be written on one.

A declaration introduces a name: a module, a constant or variable, a function, a type, a member of a type, an extension or an alias. Every declaration may be preceded by attributes (see Attributes) and modifiers. This chapter lists every declaration and every modifier, with what each permits.

The guide teaches these in Functions, Structures and Classes, Properties, Methods, Subscripts and Operators, Initialization and Deinitialization, Enums and Unions, Protocols, Generics, Extensions and Modules and Access Control.

EBNF
Declaration       = { Attribute } { Modifier } DeclarationKind ;DeclarationKind   = FunctionDecl                  | StructDecl                  | ClassDecl                  | ActorDecl                  | ProtocolDecl                  | UnionDecl                  | EnumDecl                  | ExtensionDecl                  | AliasDecl                  | VariableDecl                  | ConstDecl                  | InitDecl                  | DeinitDecl                  | PropertyDecl                  | SubscriptDecl                  | OperatorDecl ;

Modules and imports#

EBNF
CompilationUnit   = [ ShebangLine ] ModuleDecl { ImportDecl } { TopLevelDecl } EOF ;ModuleDecl        = { Attribute } "module" QualifiedName NL ;ImportDecl        = [ "public" ] "import" ImportTarget NL ;ImportTarget      = QualifiedName [ "as" Identifier ]                  | QualifiedName "." "{" ImportItem { "," ImportItem } "}"                  | QualifiedName "." "{" "*" "}" ;ImportItem        = Identifier [ "as" Identifier ] ;TopLevelDecl      = Declaration                  | ComptimeBlock                  | ConditionalCompilation ;

Every file begins (after an optional shebang) with one module declaration, naming the module the file belongs to. Module names are dotted; the root segment is the package's name. A module may span many files, with no correspondence between file and type names. Imports come next, then declarations.

Sable
module App.Renderingimport Sable.Collectionsimport Sable.Math as M                           // the module under another nameimport Sable.IO.{ File, Directory }              // chosen itemsimport Sable.Core.{ Platform, Reflect as Reflection }   // an item renamedimport Sable.Text.{ * }                          // every public item; discouraged outside a preludepublic import Sable.Math.Vectors                 // re-exported to this module's importers
  • The wildcard is braced, { * }, so that the line cannot end on *.
  • public import re-exports: consumers of this module see the imported one too.
  • Circular dependencies between modules are an error; between files of one module, they are fine.
  • An imported name is preferred over a Sable.Core name of the same spelling.

Modifiers#

EBNF
Modifier          = Visibility                  | "static" | "open" | "sealed" | "abstract" | "final"                  | "override" | "required" | "convenience" | "mutating"                  | "nonmutating" | "lazy" | "async" | "const" | "nonisolated"                  | "unsafe"                  | "weak" | "unowned" [ "(" ( "safe" | "unsafe" ) ")" ] ;Visibility        = "public" | "package" | "internal" | "private"                  | "private" "(" "set" ")" ;
Modifier On Meaning
public any Visible to every consumer of the package
package any Visible within the workspace (all packages that are members of it)
internal any Visible within the module — the default
private any Visible within the enclosing declaration, and its extensions in the same module
private(set) var Readable at the property's own visibility, settable only privately
static members, module-level let/var Belongs to the type, not an instance; at module level, a global set once before main
open class, method, property May be subclassed or overridden outside the module; members are non-virtual without it
sealed class May not be subclassed further
abstract class, member A class that cannot be instantiated; a member subclasses must implement
final class, member May not be subclassed, or overridden
override member Overrides a superclass member; mandatory when overriding
required init Every subclass must implement this initialiser
convenience init Delegates to another initialiser with self.init(…) (S3141)
mutating method, accessor, operator May change self; required to do so in a struct or union
nonmutating method Accepted by the parser; has no effect today
lazy var Computed from its initialiser on first read
async fn, init, let An async function; with let, a child task (async let)
const fn, init Callable at compile time
nonisolated actor member Callable without awaiting the actor
unsafe fn, init Safe only if the caller keeps a promise; callable only in unsafe code
weak var of class type Does not keep the object alive; optional, becomes none
unowned, unowned(safe) let/var of class type Does not keep the object alive; traps if read after it is gone
unowned(unsafe) let/var of class type As unowned, with no check

unsafe is a modifier only before fn, init or another modifier (unsafe static fn, unsafe mutating fn); before a brace it begins an unsafe block. Only a function can be unsafe (S3471).

Constants and variables#

EBNF
VariableDecl      = [ "async" ] [ "using" ] ( "let" | "var" ) BindingPattern                    [ ":" Type ] [ "=" Expression ] [ Accessors ] [ "," | ";" ] NL ;TerseFieldDecl    = Identifier ":" Type [ "=" Expression ] [ Accessors ]                    [ "," | ";" ] NL ;                    (* inside a type body only; declares an immutable field *)ConstDecl         = "const" Identifier [ ":" Type ] "=" Expression NL ;

let and var declare bindings in a body (see Statements), globals at module level, and stored properties in a type body. Inside a type body a field may be written without let: name: Type declares an immutable stored field.

Sable
struct Vec3 { x: F32, y: F32, z: F32 }       // three immutable fieldsstruct Counter {    var count = 0                             // mutable    let id: UUID                              // immutable}

Members on one line are separated by , or ;; members on their own lines need no separator.

Constants#

const declares a compile-time constant: its value is computed while compiling and written as a literal wherever it is read. Its type may be left out when its value is a literal, another constant, a call or arithmetic on those. Whatever the value calls must be a const fn, a const init, a compiler-written initialiser, or a pure member of Sable.Core (S3220). A trap while computing it is a compile-time error (S3201 for arithmetic, S3221 otherwise). See Compile-Time Evaluation.

Sable
const maxPacket = 1500const table = buildCrcTable()

Functions#

EBNF
FunctionDecl      = "fn" FunctionName [ GenericParams ] "(" [ ParamList ] ")"                    [ EffectSpec ] [ "->" ReturnType ]                    [ WhereClause ]                    FunctionBody ;FunctionName      = Identifier | QualifiedName ;   (* QualifiedName: explicit                                                      protocol implementation,                                                      e.g. fn Drawable.render *)FunctionBody      = Block                  | "=>" Expression NL                  | NL ;                            (* no body: protocol / abstract *)EffectSpec        = { "async" | ThrowsSpec } ;ThrowsSpec        = "throws" [ "(" Type ")" ] | "rethrows" ;ReturnType        = Type ;                         (* "-> Node&" returns a reference *)
Sable
fn add(_ a: Int, _ b: Int) -> Int { return a + b }fn greet(name: String) { print("hello, \(name)") }     // returns Voidfn double(_ x: Int) -> Int => x * 2                    // expression bodyfn divmod(_ a: Int, _ b: Int) -> (q: Int, r: Int) { return (q: a / b, r: a % b) }async fn fetch(_ url: Url) throws(HttpError) -> Response { }
  • Result. Without -> T, a function returns Void. A result type is always written, except that an => body's may be inferred for a non-public function. -> Never means it does not return. -> T& returns a reference rooted in a parameter, by root inference.
  • Body. A block, => expression, or none — for a protocol requirement, an abstract member, or an @extern function.
  • Effects. async makes it async: its callers await it. throws(E) says it may throw E; bare throws is throws(any Error). rethrows throws only when a closure argument does; rethrows(E) throws E as well. Effects are part of the function's type: async (…) throws(E) -> T. async may be written before fn as a modifier or after the parameters.
  • Explicit protocol implementation. fn Drawable.render() -> Image implements render for Drawable alone, when two protocols require members of the same name.
  • Overloading on parameter types, counts and labels is allowed; on the result type alone it is not.
  • Local functions may be declared in a body; see Statements.
  • const fn may be called at compile time; its body may allocate, loop and call other const fns, but not do I/O or unsafe work.
  • unsafe fn may be called, or taken as a value, only in an unsafe block or another unsafe fn (S3470).

Parameters#

EBNF
ParamList         = Param { "," Param } [ "," ] ;Param             = { Attribute } [ ParamModifier ] [ ParamLabel ] Identifier                    ":" [ ParamModifier ] Type [ "..." ] [ "=" Expression ] ;                    (* the modifier may precede the name or follow the colon;                       the second form composes with an external label.                       'in name:' is the label 'in', not the modifier:                       'fn build(in r: region)' is called 'build(in: a)' *)ParamModifier     = "inout" | "out" | "consuming" | "in" ;                    (* a parameter that refers to its argument says so in                       its type, "a: Node&"; "ref" and "borrowing" are                       reserved, and an error (S1013) *)ParamLabel        = Identifier | Keyword | "_" ;    (* external label *)
Sable
fn relocate(from source: Point, to destination: Point) { }fn insert(_ item: Element, at index: Int) { }fn connect(host: String, port: Int = 443, timeout: Duration = .seconds(30)) { }fn sum(of values: Int...) -> Int { }fn tryParse(_ s: String, out value: Int) -> Bool { }fn scale(_ v: inout Vec3, by factor: F32) { }fn store(_ handle: consuming FileHandle) { }fn area(_ r: Rect&) -> F64 { }
  • Labels. A parameter may have an external label before its name; _ means none. A parameter with a single name is called with that label or without it. A label may be a keyword: fn first(where predicate: (Element) -> Bool).
  • Defaults. = expression is evaluated at each call that leaves the argument off, in the declaration's scope; its generic parameters are what that call gives them. A default of #file, #line, #column or #function takes the call's place; #expression is described in Lexical Structure.
  • Variadic. T... takes any number of Ts, written as separate arguments.
  • Ownership. The modifier is written before the name or after the colon; the second form reads better with a label, fn read(into buffer: inout U8[]).
Parameter The callee gets The caller writes
x: T A copy (a class or @noncopy value is passed by reference) f(x)
x: T& The caller's value, read in place f(x)
x: inout T Exclusive access to the caller's variable, changed in place f(&x)
x: out T The caller's variable, which it must assign before returning f(&x) or f(out x)
x: consuming T Ownership of the value f(x) or f(move x)

ref and borrowing are not Sable (S1013): a parameter that refers to its argument says so in its type, T&. An inout, out or & argument must name a place an assignment could write.

  • Attributes on a parameter's type. @escaping, @autoclosure and @Sendable are written on the type, f: @escaping () -> Int; before the parameter they are S1014. See Attributes.
  • Region parameters. fn build(in r: region) -> Node& takes the region to allocate in. in there is the external label, not a modifier.

Generators#

A function, method, computed property or closure whose result is some Sequence<T> or some Iterator<T> (some AsyncSequence<T> or some AsyncIterator<T> for an async one) and whose body contains yield is a generator.

Sable
fn evens(upTo n: Int) -> some Sequence<Int> {    var i = 0    while i <= n {        yield i        i += 2    }}
  • Calling it runs nothing: it captures its arguments (and self) by value, and the body runs a step at a time as next() asks. Each makeIterator() starts afresh; a copy of an iterator goes on independently.
  • return with no value, or the end of the body, finishes it; return with a value is S3482. An inout or out parameter is S3483.
  • A generator declared throws(E) gives a sequence whose Failure is E, so it is iterated with for try; the call itself throws nothing. Once it has thrown, it is finished.
  • Its pending defers run when it finishes or when its iterator is dropped; a defer body may not yield (S3481).
  • yield elsewhere is S3480, as is a result that names no sequence of what is yielded.

Generic parameters and where clauses#

EBNF
GenericParams     = "<" GenericParam { "," GenericParam } ">" ;GenericParam      = { Attribute } [ "out" | "in" ] Identifier                    [ ":" TypeList ] [ "=" Type ] ;                                                 (* "N: Int", an integer type: a value parameter *)WhereClause       = "where" WhereItem { "," WhereItem } ;WhereItem         = Type ":" TypeList            (* conformance / inheritance *)                  | Type "==" Type               (* same-type constraint      *)                  | Expression ;                 (* const generic predicate   *)TypeList          = ConstraintType { "&" ConstraintType } ;   (* composition in constraints *)ConstraintType    = [ "~" ] Type ;               (* "~Copyable" lifts the implicit constraint *)

Functions, initialisers, subscripts, structs, classes, actors, protocols, unions and aliases may be generic.

Sable
fn max<T: Comparable>(_ a: T, _ b: T) -> T => a >= b ? a : bstruct Cache<Key: Hashable, Value> {    private var items: [Key: Value] = [:]}fn zip<A, B, S1, S2>(_ a: S1, _ b: S2) -> some Sequence<(A, B)>    where S1: Sequence<A>, S2: Sequence<B>, A: Sendable { }struct Ring<T, N: Int> where N > 0 { var slots: T[N] }struct Box<T: ~Copyable> { private var value: T }protocol Producer<out T> { fn next() -> T? }protocol Consumer<in T> { fn accept(_ value: T) }
Constraint Meaning
T: P Conforms to protocol P (P & Q for several)
T: Widget Is or inherits from class Widget
where S.Element == T Same-type
T: Sendable Safe to cross an isolation boundary
T: ~Copyable May be a move-only type (lifts the implicit Copyable)
N: Int A value parameter: a number, not a type
where N > 0 A predicate over value parameters, checked per instance (S3421)
where Self: P On a method: asked of each call, known in the body
  • Generic code is monomorphised: each instantiation is compiled for its types. @polymorphic opts a function into one boxed copy.
  • out and in on a protocol's parameter declare it covariant or contravariant, which makes its existentials variant; a parameter in the wrong position is S3047. Generic types are otherwise invariant.
  • A parameter may have a default type, = Type.
  • Sized (statically known size) appears in the spec as a constraint but has no compiler handling yet.

Structures#

EBNF
StructDecl        = "struct" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;TypeBody          = "{" { MemberDecl } "}" ;MemberDecl        = Declaration                  | TerseFieldDecl                  | AssociatedTypeDecl                  | ConditionalCompilation ;

A struct is a value type: assigning or passing one copies it (copy-on-write for the buffers inside). It may have stored and computed properties, methods, initialisers, subscripts, operators, static members and nested types, conform to protocols and be generic.

Sable
struct Vec3 {    var x: F32    var y: F32    var z: F32    static let zero = Vec3(x: 0, y: 0, z: 0)    var length: F32 => (x * x + y * y + z * z).sqrt()    mutating fn scale(by f: F32) { x *= f; y *= f; z *= f }    operator + (a: Vec3, b: Vec3) -> Vec3 => Vec3(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z)}
  • A struct that declares no init has a memberwise initialiser, Vec3(x:y:z:), whose parameters for fields with initial values have those defaults. It may also be made with a record literal, Vec3 { x: 1, y: 2, z: 3 }.
  • A method that changes self must be mutating.
  • A @noncopy struct is move-only and may declare a deinit.

Classes#

EBNF
ClassDecl         = "class" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;

A class is a reference type with identity, reference-counted. The first type in its list may be its superclass; the rest are protocols. Single inheritance, many conformances.

Sable
public open class Document: Serializable {    public var title: String    public weak var owner: Workspace?    public unowned let store: Store    public init(title: String, store: Store) {        self.title = title        self.store = store    }    deinit { store.unregister(self) }    public open fn render() -> String { return title }    public override fn description() -> String => "Document(\(title))"}
  • Members are non-virtual unless open or abstract; override is mandatory when overriding; final stops further overriding.
  • A class is subclassable outside its module only if open; sealed stops all further subclassing; abstract makes it uninstantiable.
  • A class with no init whose stored fields all have initial values is made with init(); a subclass with no init inherits its superclass's initialisers.
  • === and !== compare identity.

Actors#

EBNF
ActorDecl         = "actor" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] TypeBody ;

An actor is a reference type whose state is isolated: it runs one call at a time. A call into it or a read of its state from outside is awaited; a call it makes to itself is not. A nonisolated member is reached without awaiting — an immutable let, or a method that touches no isolated state. An isolated method meets a protocol's async requirement but not a synchronous one (S3237). Actors are reentrant at each await.

Sable
actor Counter {    private var value = 0    fn increment() { value += 1 }    nonisolated let id: UUID}

Protocols#

EBNF
ProtocolDecl      = "protocol" Identifier [ GenericParams ] [ ":" TypeList ]                    [ WhereClause ] ProtocolBody ;ProtocolBody      = "{" { ProtocolMember } "}" ;ProtocolMember    = { Attribute } { Modifier }                    ( AssociatedTypeDecl                    | FunctionDecl            (* body optional = default impl *)                    | PropertyDecl                    | SubscriptDecl                    | InitDecl                    | OperatorDecl ) ;AssociatedTypeDecl = "associatedtype" Identifier [ ":" TypeList ]                     [ "=" Type ] [ WhereClause ] NL ;                     (* the where clause is the protocol's: "where Iter.Element == Element" *)

A protocol declares requirements: methods, properties (with { get } or { get set }), subscripts, initialisers, operators and associated types. A requirement given a body has a default implementation.

Sable
public protocol Collection {    associatedtype Element    associatedtype Index: Comparable = Int    var count: Int { get }    subscript(i: Index) -> Element { get }    fn makeIterator() -> some Iterator<Element>    var isEmpty: Bool { get => count == 0 }      // default implementation}public protocol Sequence {    associatedtype Element    associatedtype Iter: Iterator where Iter.Element == Element    fn makeIterator() -> Iter}
  • An associated type may have constraints, a default (= Int), and a where clause, which is the protocol's: it holds of every conformer. A conformer gives it with an alias, or it is inferred from the conformer's members.
  • A protocol may refine others, protocol Error: Debug, Sendable, and have generic parameters, Producer<out T>.
  • Conformance is nominal and explicit: a type conforms only where its declaration or an extension says so. A conformance may be declared only in the type's module or the protocol's (coherence).
  • An init requirement may throw; a conformer meets it with one that throws that or nothing.

Unions#

EBNF
UnionDecl         = "union" Identifier [ ".." ] [ GenericParams ]                    [ ":" TypeList ] [ WhereClause ] UnionBody ;                    (* ".." marks a variant-sized union *)UnionBody         = "{" { UnionCase } { MemberDecl } "}" ;UnionCase         = { Attribute } Identifier [ "(" [ CasePayload ] ")" ]                    [ "," ] NL ;CasePayload       = CaseField { "," CaseField } ;CaseField         = [ Identifier ":" ] Type ;

A union is a nominal tagged sum: a value is exactly one of its cases, each with an optional payload of labelled or unlabelled fields. Cases come first in the body, then members.

Sable
public union Shape {    Circle(radius: F64)    Rect(width: F64, height: F64)    Poly(points: Vec2[>..])    Empty}public union Outcome<T, E> {    Ok(T)    Err(E)    fn map<U>(_ f: (T) -> U) -> Outcome<U, E> {        return match self {            case .Ok(let v) => .Ok(f(v))            case .Err(let e) => .Err(e)        }    }}
  • A case is made as Shape.Circle(radius: 2), or .Circle(radius: 2) where the type is known.
  • Unions may have methods, computed properties, static members and conformances, like structs.
  • A recursive case is boxed automatically; @indirect on a case, or the union, forces it.
  • union Name.. is variant-sized: each value takes exactly its case's size, so arrays of them are compact and sequential, and references may point into a payload; an existing value's case cannot be changed. See Inline Layout.
  • A public union that is not @frozen must be matched with a default in other modules.

Enumerations#

EBNF
EnumDecl          = "enum" Identifier [ ":" Type ] EnumBody ;EnumBody          = "{" EnumCase { [ "," ] EnumCase } "}" ;EnumCase          = { Attribute } Identifier [ "=" Expression ] ;

An enum is a named integer: payload-free cases with an underlying integer value. The type after : is the integer type, Int if none.

Sable
public enum Direction { North, South, East, West }public enum Status: U8 {    Pending = 0    Active = 1    Closed = 9}@flagspublic enum Permissions: U32 {    None = 0    Read = 1    Write = 2    Execute = 4    All = Read | Write | Execute}
  • A case's value is the integer expression it is given — literals, earlier cases, and | & ^ + - * << >> ~ of them — or else one more than the previous case's, starting from 0; in a @flags enum, the next bit up, starting from 1. Outside @flags, no two cases may share a value (S3142).
  • Status.Closed as U8 is a case's integer; 9 as Status is the case of an integer, trapping if there is none.
  • Interpolated, a case is its name. A @flags enum's value is any set of its cases, combined with | & ^ ~ and tested with contains; a match on one needs default.

enum and union are deliberately separate: an enum is an integer, a union a tagged sum.

Extensions#

EBNF
ExtensionDecl     = "extension" Type [ ":" TypeList ] [ WhereClause ] TypeBody ;

An extension adds members to an existing type — methods, computed properties, subscripts, operators, static members, nested types — and conformances. It may not add stored properties (nor field-backed ones) or designated initialisers.

Sable
extension String {    var isBlank: Bool => trimmed().isEmpty    init(twice s: String) { self = s + s }}extension Vec3: Serializable { }extension Array<T> where T: Comparable {    fn sorted() -> Self { }}extension Collection {    fn first(where predicate: (Element) -> Bool) -> Element? { }}
  • A struct's, enum's, union's or built-in type's extension may add an initialiser that gives self its value on every path (S3028). A class's may add a convenience init (S3141), and no other (S3030). A protocol's may add none.
  • An extension of a protocol adds members to every conformer; a member that is not a requirement is dispatched statically.
  • A conditional conformance: extension Optional<T>: Serializable where T: Serializable { }.

Extending array kinds#

An array type has no name to put parameters after, so an extension of every array of a kind declares its parameters after the keyword:

Sable
extension<Element> Element[>..] {    mutating fn appendTwice(_ e: Element) { append(e); append(e) }}extension<Element: Equatable> Element[:] {    fn contains(element: Element) -> Bool {        for x in self { if x == element { return true } }        return false    }}extension U8[:] { fn toHex() -> String { } }
  • Each kind is extended on its own: T[], T[..], T[>..], T[>..<], T[:], with no size written. Members of T[:] are every kind's.
  • Each parameter must appear in the array type. The members are an array's only where its element meets the constraints.
  • A member for a specific element type is preferred over a generic one, and a more constrained one over a less.
  • An extension of T[>..] or T[>..<] may declare initialisers, starting from self = [].

The grammar's ExtensionDecl does not show the extension<…> parameter list; the parser accepts it.

Type aliases#

EBNF
AliasDecl         = "alias" Identifier [ GenericParams ] "=" Type NL ;

alias Name = Type names a type; see Types. typealias is refused (S1012).

Initialisers#

EBNF
InitDecl          = "init" [ "?" ] [ GenericParams ] "(" [ ParamList ] ")"                    [ ThrowsSpec ] [ WhereClause ] ( Block | NL ) ;

An initialiser gives a new value every stored property before it returns (definite initialisation).

Sable
struct Temperature {    var celsius: F64    init(celsius: F64) { self.celsius = celsius }    init(fahrenheit: F64) { self.init(celsius: (fahrenheit - 32) * 5 / 9) }    init(_ text: String) throws(ParseError) { celsius = try F64.parse(text) }}
  • An initialiser may be generic, async, const, unsafe, and may throw (throws(E), bare throws, rethrows); a call to a throwing one is marked try.
  • Delegation. self.init(…) hands the work to another initialiser of the type; one that delegates leaves fields' initial values to the one it calls.
  • Classes. A subclass's initialiser calls super.init(…) on every path, or delegates with self.init(…) (S3143); only a superclass made with the implicit init() may be left to it. convenience init must delegate (S3141). required init must be implemented by every subclass.
  • Failure. An initialiser that throws part way made nothing: the fields it had set are destroyed, the others left alone, and no deinit runs (for a class, its own or a superclass's).
  • The grammar admits init?, a failable initialiser; the language does not yet give it a meaning, so it should not be used.

Deinitialisers#

EBNF
DeinitDecl        = "deinit" Block ;

deinit runs as a class instance's last reference goes, or as a @noncopy value is destroyed. It takes no parameters and cannot be called directly.

Properties and accessors#

EBNF
PropertyDecl      = ( "let" | "var" ) Identifier ":" Type Accessors ;Accessors         = "{" ( GetSetBlock | ObserverBlock | "get" [ "set" ] ) "}" ;GetSetBlock       = GetAccessor [ SetAccessor ] | SetAccessor GetAccessor ;GetAccessor       = { Attribute } [ Visibility ] "get" ( Block | "=>" Expression | NL ) ;SetAccessor       = { Attribute } [ Visibility ] "set" [ "(" Identifier ")" ]                    ( Block | NL ) ;ObserverBlock     = { ( "willSet" | "didSet" ) [ "(" Identifier ")" ] Block } ;
Sable
class Temperature {    private var celsius: F64 = 0    var fahrenheit: F64 {        get => celsius * 9 / 5 + 32        set { celsius = (newValue - 32) * 5 / 9 }    }    var kelvin: F64 => celsius + 273.15          // get-only shorthand    private(set) var updates: Int = 0    var tracked: Int = 0 {        willSet { log("becoming \(newValue)") }        didSet { log("was \(oldValue)") }    }    lazy var report: Report = computeReport()}
Kind Declared with Meaning
Stored let/var name: T = v, or name: T A field of the value
Computed { get … set … } Read and written through accessors; no storage
Get-only shorthand var name: T => e { get => e }
Observed { willSet … didSet … } after a stored var Stores call willSet (with newValue) then didSet (with oldValue)
Field-backed accessors naming field Stored, but read and written through its accessors
Lazy lazy var name: T = e e evaluated on first read, and kept
  • Accessors. Either may be => e or a block. A setter's new value is newValue, or the name it gives in set(name). An accessor may have its own visibility, and private(set) on the property restricts its setter.
  • Observers run for compound assignment too, but not for stores the observers make themselves, nor in the type's initialisers, a record literal or the memberwise initialiser. An observed property is a var, declares no get or set, and belongs to a struct, class or actor (S3140).
  • field. Accessors may refer to field, storage of the property's own. The property must then have an initial value. get or set written alone is the plain one (get => field, set => field = newValue). An extension cannot declare one.
  • lazy. A lazy var has an initialiser, which may use self, and no accessors; it belongs to a struct, class or actor (S3113). Since reading a struct's lazy property writes it, it is read only from a var or in a mutating method.
  • A brace after a stored property's initialiser opens accessors when it starts with get, set, willSet or didSet; otherwise it is a trailing closure on the initialiser.
  • weak var of a class type is optional and becomes none when the object is released; unowned is not optional, and traps when read after release; unowned(unsafe) does not check.
  • Static stored properties are initialised before main, like globals.

Subscripts#

EBNF
SubscriptDecl     = "subscript" [ GenericParams ] "(" [ ParamList ] ")"                    "->" Type [ WhereClause ] ( Accessors | "=>" Expression NL ) ;

A subscript lets an instance be indexed, grid[x: 1, y: 2]. Its parameters follow function rules, including labels; its accessors follow property rules.

Sable
struct Grid<T> {    subscript(x: Int, y: Int) -> T {        get => storage[y * width + x]        set { storage[y * width + x] = newValue }    }    subscript(row r: Int) -> T[:] => storage[r * width ..< (r + 1) * width]}

Operator declarations#

EBNF
OperatorDecl      = [ "prefix" | "postfix" ] "operator" OperatorSymbol                    "(" [ ParamList ] ")" "->" Type ( Block | "=>" Expression NL ) ;OperatorSymbol    = "+" | "-" | "*" | "/" | "%" | "&" | "|" | "^"                  | "<<" | ">>" | "==" | "!=" | "<" | "<=" | ">" | ">="                  | "[" "]" | "(" ")" | "!" | "~" ;

A type may overload operators for its values, as members taking every operand as a parameter:

Sable
struct Money {    var cents: Int    operator + (a: Money, b: Money) -> Money => Money(cents: a.cents + b.cents)    operator == (a: Money, b: Money) -> Bool => a.cents == b.cents    operator < (a: Money, b: Money) -> Bool => a.cents < b.cents    prefix operator - (m: Money) -> Money => Money(cents: -m.cents)}
  • Overloadable: binary + - * / % & | ^ << >> == != < <= > >=, [] (an alternative subscript form) and (), and prefix - ! ~.
  • Not overloadable: && || ?? ?. = . as is, and compound assignments, which are derived from the binary operator.
  • postfix operator declarations parse, but a user-declared postfix operator is resolved only for !; treat them as limited.
  • There are no custom operator symbols, and precedence is fixed.
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.