DocsLanguage Reference
Attributes
Every attribute the language knows, where it applies and what it does.
An attribute gives the compiler, or a tool, more information about a declaration or a type. It is written @name, with arguments in parentheses when it takes any, before the declaration's modifiers. Sable has no macros: every attribute is either one the language defines, listed in this chapter, one a source generator answers to, or a struct of the program's own conforming to Attribute. An attribute nothing knows is an error, never silently ignored.
Most attributes are introduced in the guide where their feature is: Memory and Ownership, Inline Layout, Derivation and Source Generators, Unsafe Code and C Interop, Documentation and Testing.
Attribute syntax#
Attribute = "@" QualifiedName [ "(" [ AttributeArgs ] ")" ] ;AttributeArgs = AttributeArg { "," AttributeArg } ;AttributeArg = [ Identifier ":" ] Expression ;@inline(always)fn square(_ x: Int) -> Int => x * x@derive(Equatable, Hashable)@reflectablepublic struct Point { var x: Int, var y: Int }fn on(_ handler: @escaping () -> Void) { }Attributes may be written on declarations of every kind — module, type, function, initialiser, deinitialiser, subscript, operator, property, accessor, constant, alias, associated type, union and enum case, parameter, generic parameter — and on the type of a parameter. Several may be written, on one line or several.
Validation#
The compiler checks every attribute:
| Diagnostic | When |
|---|---|
| S3092 | The name is no attribute: not in this chapter, not a generator's, not a struct conforming to Attribute, and not a validation rule |
| S3093 | The attribute does not apply where it is written (@flags on a struct) |
| S3094 | Its arguments are not ones it takes (@inline(sometimes)) |
| S3513 | It is written twice on one declaration |
| S3511 | An argument of a user-defined attribute is not a constant |
| S1014 | @escaping, @autoclosure or @Sendable written before a parameter rather than on its type |
@derive, @allow, @warn and user-defined attributes may be repeated on one declaration; the compiler also accepts a repeated @builtin, @extern and @export, checking those where they are read.
Optimisation#
| Attribute | Applies to | Effect |
|---|---|---|
@inline(always) |
function | Inlined at every call (except into itself, and except one that throws) |
@inline(never) |
function | Never inlined |
@inlinable |
function | A library's generic function whose body its interface carries, so an optimised program specialises it whatever its size |
@vectorised |
function | Compiled also for wider vectors the processor may have (AVX2 on x86-64), the best chosen at run time |
@reassociate |
function | Its own floating-point + - * / may be regrouped, so float reductions vectorise |
@polymorphic |
generic function | One boxed instantiation instead of one per type |
@inlinetakes exactlyalwaysornever. It works through both the SIL inliner and LLVM's (alwaysinline,noinline).- Without
@inlinable, only small library generics and@inline(always)ones are specialised across the library boundary. @vectorisedis for loops overSIMDvectors, or ones LLVM vectorises. Such a function is not inlined where it is called, and is compiled once if it passes a vector to a function not inlined in it.@reassociateis LLVM'sreassoc: results may differ in their last bits from the written order. It covers the function's own arithmetic, not its closures' or callees', and is kept where the function is inlined.@polymorphicpasses each value of a type parameter boxed with its witness table. Its type parameters must be constrained to protocols alone, with no associated types orSelfrequirements; each parameter and the result must be a type parameter or mention none; none may beinout(S3512). Taken as a value, the function is still compiled per type.
@inline's argument aside, these attributes take no arguments.
Layout and memory#
| Attribute | Applies to | Effect |
|---|---|---|
@inline_layout |
struct, union | Contiguous, pointer-free layout: the value is its bytes |
@noncopy |
struct, union | Move-only; may declare deinit |
@immutable |
class | Deeply immutable, and therefore Sendable |
@immortal |
static let |
Never released: reference counting is skipped |
@packed |
struct | Fields laid out with no padding; aligned to a byte |
@align(n) |
struct | Aligned to at least n, its size rounded up to a multiple |
@indirect |
union, union case | The case's payload (or every case's) is boxed |
@inline_layoutstruct Packet { header: U32 payload: U8[..1500]}@noncopy struct Lock { private let handle: RawPtr<Opaque> deinit { sys.unlock(handle) }}@packed @align(4)struct WireHeader { kind: U8, length: U16 }@indirect union Path { Then(Path, Move) Start}@align(n)takes a power of two up to 16, the alignment of every block the runtime allocates; more is S3510. With@packed, the struct is aligned to exactlyn. Both are C's layouts (__attribute__((packed)),_Alignas(n)), and a struct passed to or from C is passed as C passes its own. A field of a packed struct passedinoutis copied to an aligned place and back. On an@inline_layoutstruct,@align(n)places the struct at a multiple ofnwithin a value that holds it.- A recursive union case is boxed automatically;
@indirectforces it. @immortalapplies to astatic letonly.
Types and conformances#
| Attribute | Applies to | Effect |
|---|---|---|
@reflectable |
type | Conforms it to Reflectable: TypeInfo.of describes it at run time |
@reflectable(callable) |
type | Conforms it to Callable too: its public initialisers, methods and operators can be called with boxed arguments, and it is listed among a protocol's conformers |
@flags |
enum | The enum is a bit set; values are sets of cases |
@frozen |
union | The union never gains a case: other modules may match it without default |
@derive(…) |
struct, union, enum | The compiler writes the named conformances |
@serialize(…) |
type, property, case | Tunes a derived Serializable |
@reflectable(callable) is not allowed on a move-only type (S3080). Its only argument is callable.
@derive#
@derive names the conformances for the compiler to write, from the type's fields or cases. It applies to structs, unions and enums, not classes.
| Protocol | From | Writes |
|---|---|---|
Equatable |
Sable.Core | ==, field by field or case then payload |
Comparable |
Sable.Core | <, in field order, or cases in declaration order |
Hashable |
Sable.Core | hash(into:), a union's case first |
Debug |
Sable.Core | A description of the value, an enum case as Direction.East |
Serializable |
Sable.Serialize | encode(to:) and decode(from:), generic over the format |
Arbitrary |
Sable.Testing | Random values for property tests and fuzzing |
Validatable |
Sable.Validation | Validation rules, from its fields' attributes |
Copy |
— | Nothing: asserts the type is copied, an error on a @noncopy type |
@derive(Equatable, Hashable, Comparable, Debug)struct Version { major: Int, minor: Int, patch: Int }HashableandComparablebringEquatablewith them, unless the type writes its own==.- On a generic type the conformance is conditional:
@derive(Equatable)onPair<T, U>holdswhere T: Equatable, U: Equatable. - A
@flagsenum derives onlyEquatable,HashableandDebug, by its integer; it is never ordered. - Any other name is an error naming the ones
@deriveknows.
@serialize#
@serialize adjusts what a derived Serializable writes. Every option is checked where it is written.
| Option | On | Effect |
|---|---|---|
renameAll: .SnakeCase |
type | Keys from field names by a policy: .CamelCase, .PascalCase, .SnakeCase, .ScreamingSnakeCase, .KebabCase |
rename: "id" |
property, case | This key instead of the name |
skip |
property | Never written; its initial value when read |
defaulted |
property | Its initial value when the key is missing |
flatten |
property | Its members written among this struct's own (a map: the keys left over) |
tag: "type" |
union | Internally tagged: {"type": "Click", "x": 1} |
tag: "t", content: "c" |
union | Adjacently tagged: {"t": "Text", "c": "hi"} |
untagged |
union | The payload alone; read as the first case it decodes as |
@derive(Serializable)@serialize(renameAll: .SnakeCase)struct Account { var userName: String @serialize(rename: "id") var accountNumber: Int @serialize(defaulted) var retries: Int = 3}A flattened field must be written as a struct or a map, and must not write a key twice (S3071).
Validation rules#
On a field of a struct that derives Validatable, any attribute that is none of the language's, nor a generator's, nor the program's own, is a rule: a method of FieldRules by its name, called with its arguments, in order, on that field's rules. A name that is no rule for the field's type is S3092.
@derive(Validatable)struct Signup { @notEmpty @email var email: String @range(18...) @message("You must be an adult.") var age: Int}Functions and closures#
| Attribute | Applies to | Effect |
|---|---|---|
@escaping |
a parameter's function type, or a function type's parameter | The closure may outlive the call |
@autoclosure |
a parameter's type () -> T |
The argument, written as a T, becomes a closure the callee calls when it wants the value |
@Sendable |
a parameter's function type | The closure runs as a task: its captures must be Sendable |
@discardable |
function | Its result may be ignored without _ = and without the unused_result warning |
@main |
function | The program's entry point |
@MainActor |
any declaration | Isolated to the main executor, the main thread |
- These three are written on the parameter's type,
f: @escaping () -> Int; before the parameter they are S1014, with a fix that moves them. @escapingis part of the function type:(@escaping () -> Int) -> Voidmay keep its closure,(() -> Int) -> Voidmay not. A non-escaping closure may only be called or passed to another non-escaping parameter (S3205). An override or a protocol witness may not add@escapingto a parameter the original lacks (S3210). Of a function type's parameter or a closure's,@escapingis the only attribute that may be said.@autoclosure: the parameter takes nothing and is notasync, variadic,inout,outorconsuming(S3515). The closure is non-escaping unless the parameter is@escapingtoo. A default value is wrapped as an argument is. What the expression throws is the closure's, so the type says() throws -> Tand the argument is written withtryinside. Passing an@autoclosureparameter on to another means calling it there,assert(c());assert(c)is S3516. An optimised build inlines the closure away.@Sendableapplies to a closure parameter run as a task; it takes a closure written there, a named function, or another@Sendableparameter. Avaris captured only by value (S3236).@mainmarks a module-level function taking nothing and returning nothing or anIntexit status; not generic, not a method; one per module (S3514). The program's arguments areEnvironment.arguments().
fn assert(_ condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = "") { }@discardablefn insert(_ value: Int) -> Bool { }@mainfn start() -> Int { return run(Environment.arguments())}Availability#
| Attribute | Applies to | Effect |
|---|---|---|
@deprecated, @deprecated("message") |
any declaration | A warning at each use, unless the use is itself deprecated |
@available(platform, …) |
any declaration | A use in a build for another platform is S3096 |
@deprecated takes at most one string. @available names one or more of macos, linux, windows and wasi, and takes no versions.
@deprecated("use parse(_:options:)")public fn parse(_ text: String) -> Document { }@available(macos, linux)public fn watch(_ path: String) -> some AsyncSequence<FileEvent> { }Interop and the standard library#
| Attribute | Applies to | Effect |
|---|---|---|
@extern("c", "name"), @extern("c") |
function | A C function, imported; with one argument, the C name is the function's |
@export("c", "name"), @export("name") |
function, variable | Exported to C under that name; with one argument, the language is C |
@builtin("name"), @builtin |
function, variable | The standard library's alone: a body that is the named SIL builtin, or with no name, one the compiler writes per use |
- An
@externor@exportfunction is a module-level function, not generic, notasync, not throwing; an@externone has no body (S3223). What crosses is passed by value and must be a type C has the same way: integers,F32,F64,Bool,RawPtr, or a struct of those (S3224). An@externfunction taking a pointer must beunsafe fn(S3225). A variadic C function takesCVarArg.... @export("name") var count: Int = 0lets C read and write the variable's storage by that name.@builtinwith no name is allowed only in Sable.Core and Sable.Interop.
See Unsafe Code and C Interop.
Testing#
| Attribute | Applies to | Effect |
|---|---|---|
@test, @test(…) |
function | A test, run by sable test |
@suite, @suite(…) |
struct, class | A type whose instance methods are tests |
@bench |
function | A benchmark, run by sable bench |
@fuzz, @fuzz(mutator: f) |
function | A fuzz target, run by sable fuzz under libFuzzer |
@test options:
| Option | Effect |
|---|---|
arguments: [...] |
Run once per element (tuples for several parameters), or per pair given an array per parameter; each case is reported as a test of its own |
tags: [...] |
What --filter selects by, and what reports carry |
timeout: .seconds(5) |
Fail it if it runs longer (.milliseconds, .seconds, .minutes of a literal) |
traps, traps: "text" |
It passes by trapping (with that message) |
retry: 3 |
Tried again while it fails, so many times more |
skip: "why", skip(if: condition, "why") |
Not run, and reported as skipped |
explicit |
Run only when asked for by --exact or --explicit |
serialized |
Not run at the same time as another so marked in its suite |
collection: "name" |
Not run at the same time as another of the collection |
@suite takes the same options except arguments and traps; its type is made anew for each test by the initialiser whose parameters are all fixtures, and its options apply to its tests, which may override them. A @fuzz function takes a U8[:], or one to four Arbitrary values, and fails by trapping or throwing; mutator: names a function of the module, taking an input and a U64 seed, that makes other inputs.
@test(arguments: [("1", 1), ("-7", -7)], tags: ["fast"], timeout: .seconds(5))fn parses(_ text: String, _ value: Int) throws { expect(try Int.parse(text) == value)}See Documentation and Testing.
Lint levels#
@allow(lint, …) and @warn(lint, …) set the level of the named lints for one declaration and everything in it, overriding the package's [lints] table. They may be repeated.
| Lint | Reports |
|---|---|
unused_local |
A local binding never read |
unused_parameter |
A parameter the body never reads (outside overrides and requirements) |
unused_private |
A private function or type nothing uses |
unused_import |
An import the file uses nothing from |
unused_result |
A call's result left unused, where the function is not @discardable |
shadowed_local |
A local in an inner block hiding one from an outer block |
shadowed_parameter |
A local hiding a parameter (if let x = x is not one) |
var_never_mutated |
A var that could be a let |
let_discard |
let _ = f(), which should be _ = f() |
self_assignment |
x = x |
constant_arithmetic |
Integer arithmetic on constants that always traps |
@allow(unused_parameter)fn handler(_ request: Request) -> Response { return .ok }Source generators#
@generator("json", members: ["key", "skip"])fn json(_ declaration: Declaration, into output: inout Output) { }@generator("name") marks a function in a package's generators/ directory as a source generator (anywhere else it is S3093: nothing would run it). It runs as the package builds: a declaration generator, whose first parameter is a Declaration, once for every declaration marked @name or @name(…); a package generator, taking a Package, once with all of them. members: lists the attributes it reads on fields, cases and parameters, which become valid there; always: true runs a package's generator for every package. See Derivation and Source Generators.
A file may use the attributes of generators its package can see — its own and its dependencies', and a library module's when it imports the module. The standard library's:
| Module | On a type | On members |
|---|---|---|
| Sable.DependencyInjection | @injectable, @container |
@keyed, @inject, @include, @singleton, @scoped, @transient |
| Sable.Syntax | @syntax |
@base, @category, @kinds, @trivia |
| Sable.Testing | @mockable (writes Mock<Name>) |
— |
User-defined attributes#
A struct conforming to Attribute (Sable.Core) is an attribute of the program's own, written by the struct's name:
struct Route: Attribute { var path: String var method: String = "GET"}@reflectable@Route("/users", method: "POST")struct Users { }for route in TypeInfo.of(Users.self).attributes(of: Route.self) { print(route.path)}- Its arguments are checked as a call to one of the struct's initialisers, and must be constants: literals, cases, and arrays and tuples of them (S3511). The struct may not be generic.
- It may be written on any declaration, and more than once.
- On a
@reflectabletype,attributes(of:)gives the values of one attribute type in the order written.
Not implemented#
spec/SYNTAX.md mentions two attributes the compiler does not yet know; writing either is S3092:
@comptimeon a function. Use aconst fn, or acomptime { }block, which work.@safe, for marking a foreign signature as safe.