Contents Open

DocsLanguage Guide

Derivation and Source Generators

Conformances the compiler writes for you, and generators that write code as a package builds.

Much of the code in a typical program is predictable from the shape of a type: an == that compares every field, a hash that combines them, a description that prints them, a way to turn the value into JSON and back. Writing that code by hand is tedious and easy to get wrong when a field is added later.

Sable gives you two ways to have it written for you. Derivation, @derive(...), asks the compiler to write the standard library's common conformances for a struct, a union or an enum. Source generators cover everything else: they are ordinary Sable functions, shipped in a package, that read the declarations you mark and write new Sable source that is compiled with your package. Neither can change code you wrote; they only add to it. The previous chapter explained why Sable has no macros; this one shows what it has instead.

Deriving Conformances#

You ask for a conformance to be derived by writing @derive on the type, naming the protocols:

Sable
@derive(Equatable, Hashable, Debug)struct Point {    var x: I32    var y: I32}@mainfn main() {    let a = Point(x: 1, y: 2)    let b = Point(x: 1, y: 2)    print(a == b)    print(a)}
truePoint(x: 1, y: 2)

Point now conforms to Equatable, Hashable and Debug, exactly as if you had written extension Point: Equatable { ... } and the rest yourself. It can be a dictionary key, it can be compared with ==, and interpolating it describes its fields.

@derive knows these protocols:

Protocol From What it writes
Equatable Sable.Core ==, field by field
Comparable Sable.Core <, field by field in declaration order (lexicographic)
Hashable Sable.Core hash(into:), each field fed to the hasher in order
Debug Sable.Core debugDescription(), the value as source would write it
Serializable Sable.Serialize encode(to:) and decode(from:), for any format
Arbitrary Sable.Testing arbitrary(from:), random values for property tests
Validatable Sable.Validation the validation rules written as attributes on its fields
Copy nothing: it states that the type is copied, which the compiler checks

The last three come from library modules, so the file must import the module (import Sable.Serialize, import Sable.Testing, import Sable.Validation); the compiler tells you which one if you forget. A name @derive doesn't know is S3070.

A few rules apply to every derivation:

  • Hashable and Comparable both refine Equatable, so asking for either brings == too, unless the type already declares its own ==, which is then used.
  • If the type declares a member that a derivation would write, and you named that derivation explicitly, it is an error: drop one or the other. There is nothing for @derive to make.
  • Each field's type must itself conform. A Point whose fields are I32 can derive Hashable because I32 is Hashable.
  • @derive(Copy) on a @noncopy type (see Memory and Ownership) is an error: that type is moved, never copied.

Problems with a derivation are reported at the @derive (S3071).

Only values derive#

@derive is for structs, unions and enums. A class or actor cannot derive, because its objects have identity: two Account objects with equal fields are still two accounts, and an == built from the fields would say otherwise. A class that wants value equality writes == and hash(into:) itself, deciding what equality means for it.

Derived members are compiler-written, not generated text#

Derivation is not source generation. The compiler builds the derived members directly from the type's fields, as if they had been type-checked from source, and nothing is parsed. That means a derived member can never report an error against text you didn't write. It also means derivation works on every type you declare, with no package to depend on.

Deriving for Structs#

For a struct, each derived member works through the stored fields in the order they are declared.

Comparable orders by the first field, then breaks ties with the second, and so on, which is what you want for something like a version number:

Sable
@derive(Equatable, Comparable, Debug)struct Version {    let major: Int    let minor: Int}let installed = Version(major: 1, minor: 9)let latest = Version(major: 2, minor: 0)print(installed < latest)                   // prints trueprint(installed.compare(latest))           // prints Less

Debug writes the type's name and each field labelled, and the #? format spec from Strings and Characters lays it out over several lines:

Sable
@derive(Debug)struct Order {    let id: Int    let items: String[>..]    let note: String?}let order = Order(id: 7, items: ["pen"], note: none)print("\(order)")print("\(order:#?)")
Order(id: 7, items: ["pen"], note: none)Order(    id: 7,    items: [        "pen",    ],    note: none,)

Deriving for Unions and Enums#

Unions (from Enums and Unions) derive by case and payload:

  • == is true when both values are the same case with equal payloads.
  • < orders by case, in the order the cases are declared, and then by payload within a case.
  • The hash combines the case's position with its payload.
  • Debug writes the case with its payload, Shape.Circle(radius: 1.5), or just Shape.Empty for a case that carries nothing.
Sable
@derive(Equatable, Comparable, Debug)union Priority {    Low    Normal    High(reason: String)}print(Priority.Low < Priority.High(reason: "outage"))     // prints trueprint(Priority.High(reason: "outage").debugDescription())   // prints Priority.High(reason: "outage")

A recursive union derives in the same way. Here @indirect (see Enums and Unions) boxes the union's recursive case:

Sable
@derive(Debug, Arbitrary)@indirectunion Path {    Then(Path, Move)    Start    Jump(to: Int)}

An enum, which is a named integer, derives Equatable, Hashable, Comparable and Debug: cases compare equal when they are the same case, are ordered as they are declared, and are described as Direction.East.

A @flags enum is different, because its value is a set of cases. It may derive Equatable, Hashable and Debug only, which work on the integer the value is. It is described as the case it is exactly, Permissions.Read, or otherwise as Permissions(3). Sets have no natural order, so Comparable is an error:

Sable
@flags@derive(Equatable, Hashable, Debug)enum Permissions: U32 {    Read = 1    Write = 2    Execute = 4}let p: Permissions = [.Read, .Write]print(p.debugDescription())                 // prints Permissions(3)print(Permissions.Read.debugDescription())  // prints Permissions.Read

Deriving for Generic Types#

On a generic type, a derived conformance is conditional. Pair<A, B> below is Equatable whenever A and B are, and not otherwise:

Sable
@derive(Equatable, Hashable)struct Pair<A, B> {    var first: A    var second: B}let ok = Pair(first: 1, second: "one") == Pair(first: 1, second: "one")   // true

Pair<Int, String> is Equatable because both arguments are. A Pair of a type that isn't Equatable simply isn't Equatable itself, which you'd discover only if you tried to compare one. This is the same as writing extension Pair: Equatable where A: Equatable, B: Equatable { ... } by hand (see Generics).

A field whose type mentions none of the type parameters, and doesn't conform, can never make the conformance hold. That is reported at the declaration, naming the field.

Serialization#

@derive(Serializable) makes a type readable and writable in any format Sable.Serialize supports, JSON among them. The derived conformance is written at compile time; nothing is looked up by reflection as the program runs.

Sable
import Sable.Serialize@derive(Serializable, Equatable, Debug)struct Item {    var name: String    var price: F64}@derive(Serializable, Equatable, Debug)struct Order {    var id: Int    var items: Item[>..]    var note: String?}@mainfn main() throws(SerializeError) {    let order = Order(id: 7, items: [Item(name: "pen", price: 2.5)], note: none)    let text = try Json.encode(order)    print(text)    let back = try Json.decode(Order.self, from: text)    print(back == order)}
{"id":7,"items":[{"name":"pen","price":2.5}],"note":null}true

The default shapes are:

  • A struct is an object of its fields.
  • An enum is its case's name.
  • A union's case is tagged externally: {"Circle": {"radius": 1}}. A case that carries nothing is its bare name, "Empty".
  • A union payload of one unlabelled value is that value; of labelled values, an object; of several unlabelled values, an array.

When reading, a missing optional field becomes none, and keys the type doesn't know are ignored.

Tuning with @serialize#

@serialize(...) adjusts the shape. It can be written on the type and on its fields, and every option is checked where it is written.

On a struct and its fields:

Sable
@derive(Serializable)@serialize(renameAll: .SnakeCase)struct Account {    var userName: String              // "user_name"    @serialize(rename: "id")    var accountNumber: Int            // "id"    @serialize(skip)    var session: String = ""          // never written; its initial value when read    @serialize(defaulted)    var retries: Int = 3              // its initial value when the key is missing    @serialize(flatten)    var contact: Contact              // its fields among Account's own    @serialize(flatten)    var extra: Dictionary<String, Int>   // whatever keys are left over}
Option Where Effect
renameAll: .SnakeCase type renames every field; also .CamelCase, .PascalCase, .ScreamingSnakeCase, .KebabCase
rename: "name" field this field's key
skip field never written; read back as its initial value
defaulted field its initial value when the key is missing
flatten field its members are written among the containing struct's own
tag: "key" union internally tagged
tag: "t", content: "c" union adjacently tagged
untagged union the payload alone

flatten only makes sense for something written as an object or a map: a derived struct, an internally or adjacently tagged union, a dictionary, or a type parameter (which is checked when the value is encoded). Flattening a field of any other type, or one that would write the same key twice, is an error at the field (S3071). A flattened dictionary collects whatever keys are left over when reading.

On a union, the options choose how the case is recorded:

Sable
@derive(Serializable)@serialize(tag: "type")union Event {    Click(x: Int, y: Int)      // {"type": "Click", "x": 1, "y": 2}    Idle                       // {"type": "Idle"}}@derive(Serializable)@serialize(tag: "t", content: "c")union Message {    Text(String)               // {"t": "Text", "c": "hi"}}@derive(Serializable)@serialize(untagged)union Id {    Number(Int)                // 3    Name(String)               // "x"    Unknown                    // null}

An untagged union is read as the first case its data decodes as, so the order of the cases matters. At most one case of an untagged union may carry nothing, and it is written as null.

Encoders and decoders#

A Serializable conformance, derived or hand-written, is generic over the format:

Sable
public protocol Serializable {    fn encode<E: Encoder>(to encoder: E) throws(SerializeError)    static fn decode<D: Decoder>(from decoder: D) throws(SerializeError) -> Self}

An Encoder is told the value's parts in order (beginStruct, encodeField, the field's value, ..., endStruct; likewise for sequences, maps and union cases), with counts for formats that need to write them first. A Decoder is a value that can be asked for its parts, each as another decoder, and can be asked more than once, which is how an untagged union tries one case after another. A format implements both and then serves every Serializable type. JSON, CBOR, MessagePack and TOML are in Sable.Serialize, with XML and YAML in modules of their own.

In JSON, a struct and a map are objects, bytes are a base64 string, a Duration is its whole nanoseconds and a DateTime an ISO 8601 string in UTC.

Validation from Attributes#

@derive(Validatable), from Sable.Validation, turns attributes on a struct's fields into validation rules. Any attribute on a field that is not one of the language's own, not a source generator's and not one of your program's attribute structs is read as a rule: a method of FieldRules with that name, called with the attribute's arguments, in the order written.

Sable
import Sable.Validation@derive(Validatable)struct Signup {    @notEmpty    @email    var email: String                // rules.field(\.email).notEmpty().email()    @range(18...)    @message("You must be an adult.")    var age: Int    @length(8...64)    @matches("[0-9]")    var password: String    @equal(\.password)    var repeated: String    var referrer: String = ""        // no attributes, no rules}@mainasync fn main() {    let form = Signup(email: "", age: 15, password: "password", repeated: "pass", referrer: "")    let result = await form.validate()    print(result.isValid)    print(result.messages(at: "age"))}
false["You must be an adult."]

Because each rule is an ordinary method call, its arguments are type-checked where you write them: @range("eighteen") is an error on that line. A rule your program adds, as a method in an extension of FieldRules, is an attribute just as the library's are. An attribute name that is no rule for a field of that type is S3092. Validatable derives for structs only.

Source Generators#

What @derive doesn't cover, a source generator can. A generator is a Sable function, marked @generator("name"), that the compiler runs while it builds a package. It is given a description of each declaration that carries the attribute @name, and returns new Sable files. Those files are compiled with the package as if someone had written them by hand. This is the model of C#'s Roslyn source generators: generated code is added beside yours, never woven into it.

Here is a small JSON package whose generator writes a JsonWritable conformance for every type marked @json:

Sable
// json/generators/json.sbmodule JsonGeneratorsimport Sable.Generatorsimport Sable.Text@generator("json", members: ["rename", "skip"])fn json(_ declaration: Declaration, into output: inout Output) {    let body = TextBuilder()    body.appendLine("extension \(declaration.name): JsonWritable {")    body.appendLine("    public fn writeJson(into w: inout JsonWriter) {")    body.appendLine("        w.beginObject()")    for field in declaration.fields {        if field.attribute(named: "skip") != none {            continue        }        let key = field.attribute(named: "rename")?.string(named: "") ?? field.name        body.appendLine("        w.field(\"\(key)\", self.\(field.name))")    }    body.appendLine("        w.endObject()")    body.appendLine("    }")    body.appendLine("}")    output.add(file: "\(declaration.name).json.sb", body.build())}

And an application that uses it, after adding the json package as a dependency:

Sable
// app/src/model.sbmodule Appimport Json@jsonpublic struct User {    var name: String    @skip    var passwordHash: String    var age: Int}

App now has an extension User: JsonWritable that nobody wrote. It is in the build, in your editor and in the debugger like any other file.

Where Generators Live#

A package's generators are the files in its generators/ directory, beside src/, tests/ and benches/ (but not generators/tests/, which holds the generators' own tests). They are not part of the package's library or binaries, and nothing ever links them. The compiler builds them into a separate generator program and runs it in its interpreter.

A generator is a top-level function with @generator("name"). name is the attribute it answers to: @generator("json") runs for every declaration carrying @json or @json(...). A package may have any number of generators, but no two with the same name.

Declaration and package generators#

There are two kinds, told apart by the first parameter:

Sable
// Run once for each declaration that carries @json.@generator("json")fn json(_ declaration: Declaration, into output: inout Output)// Run once for the whole package, with every declaration that carries @route.@generator("route")fn routes(_ pkg: Package, into output: inout Output)

A declaration generator sees one declaration at a time. Each run depends on that one declaration alone, so its result can be cached and reused until the declaration changes.

A package generator sees every marked declaration at once. Use one when the output needs the whole set: a table of routes, a registry of services, a list of commands. It runs when at least one declaration carries its attribute.

Sable
@generator("route")fn routes(_ pkg: Package, into output: inout Output) {    let table = TextBuilder()    table.appendLine("public let routeTable: (String, String)[>..] = [")    for declaration in pkg.declarations {        let path = declaration.trigger.string(named: "") ?? "/"        table.appendLine("    (\"\(path)\", \"\(declaration.name)\"),")    }    table.appendLine("]")    output.add(file: "Routes.sb", table.build())}

Generator options#

@generator takes three options besides the name:

  • members: [...] names the attributes the generator reads on fields, cases, initialisers, methods and parameters. The compiler rejects attributes it doesn't know (S3092), so @generator("json", members: ["rename", "skip"]) is what lets a user write @rename(...) and @skip inside a @json type. Written anywhere else, they are S3093.
  • always: true runs a package generator for every package that can see it, even one with no marked declaration. That is how a generator adds code unconditionally, such as helper types its other output uses, or types generated from input files.
  • with: ["other"] also gives the generator the declarations that carry @other, and runs it for them. After its own package's declarations, it is given those of every package its package depends on, directly or not, each with its packageName. That is how a generator reads what a dependency declares.

Which Declarations a Generator Sees#

A generator runs over two kinds of package: the package that contains it, and every package that depends on that package directly (and that package's tests, when it is a dev-dependency). So writing @json in your package takes exactly one thing: depending on the package whose generator answers to json.

A transitive dependency's generators do not apply. If they did, adding a dependency deep in the graph could silently change what your package compiles to.

A generator is given the declarations that carry its attribute, of these kinds:

  • structs, classes, actors, unions, enums and protocols, at the top level of a file or nested in another type,
  • functions at the top level of a file, and methods in a type or an extension.

Two visible generators with the same name are an error (S3230), and so is a generator named after a built-in attribute (derive, inline, test and the rest), because the attribute would mean two things.

What a Generator Is Given#

Sable.Generators describes each declaration as plain data, a Declaration value, not the compiler's internal symbols. Its main members:

Member What it is
keyword "struct", "class", "actor", "union", "enum", "protocol" or "fn"
name, typeName, qualifiedName its name; with its generic parameters; with the types it is nested in
container for a nested type or a method, the type it is in (Outer.Inner), else ""
moduleName, file, imports the module and file it is in, and that file's imports
isPublic, isStatic, isFinal its modifiers, and whether nothing derives from it
typeParameters, constraints its generic parameters, and what they must be
conformances, allConformances its base list as written; every protocol it conforms to, wherever declared
superclass a class's superclass, or none
type, supertypes the type as a TypeRef, and what it derives from and conforms to
trigger the attribute that started this run, with its arguments
attributes every attribute on the declaration
fields a type's stored fields: name, type, whether var, whether it has a default, its attributes
cases a union's cases and payloads, or an enum's cases and raw values
initializers, methods, properties a type's own members, or a protocol's requirements (with those of protocols it refines)
parameters, returnType, returned a function's parameters, and its return type as written and resolved
isAsync, isThrowing a function's effects
packageName for a dependency's declaration given through with:, its package
location where it is, for messages

When there is no initialiser declared, initializers holds the memberwise one.

Types, as written and resolved#

Every type is given twice. type on a field is the text as written (String?, Int[>..], Pair<A, B>); resolved is a TypeRef, what the compiler resolved it to. A TypeRef has a kind ("struct", "optional", "array", "dictionary", "tuple", "function", "parameter" for a generic parameter, "unresolved" and so on), a name, moduleName, qualifiedName and full text, its generic arguments, its conformances and the attributes on its declaration.

That lets a generator ask questions about a field's type:

Sable
for field in declaration.fields {    if field.resolved.kind == "array" && field.resolved.arguments[0].conforms(to: "Equatable") {        // an array of Equatable values    }    if field.resolved.has(attribute: "json") {        // the field's type is itself @json    }}

What resolves is what the package declares, what its dependencies declare, and what their generators wrote. The package's own generators' output is not there, because one generator's output is never another's input. An unresolved type is "unresolved"; generated code that uses it is still type-checked, so a real mistake is still reported.

Arguments#

An attribute's argument is given as its label and its source text, and a string literal also as its value. With @json(rename: "user_name"):

Sable
declaration.trigger.argument(named: "rename")   // "\"user_name\"", the source textdeclaration.trigger.string(named: "rename")     // "user_name", the string's value

Fields, cases and parameters have attributes too, read the same way: field.attribute(named: "skip").

Input files#

A package generator is given a Package: its name, its declarations in source order, and its inputs. Inputs are files the manifest lists for its generators, each a directory (every file under it) or a single file:

Sable
// package.sblet manifest = Package {    name: "api",    version: "1.0.0",    generatorInputs: ["schemas/"],}

Each input is given as its path, relative to the package, and its text; pkg.input("schemas/user.json") finds one. Their contents are part of the generator's input and its cache key, which is how a generator can use data from outside the program without breaking its rules. A listed file that doesn't exist is a manifest error.

What a Generator Gives Back#

Output collects what a run produces:

Sable
output.add(file: "User.json.sb", text)                  // a new source fileoutput.add(file: "Routes.sb", text, inModule: "Api")    // in a module the package choosesoutput.error("@json cannot be put on a union")           // the build fails, at the attributeoutput.warning("'cache' is not written", at: field.location)  // a warning, at the field

A message is reported at the attribute that started the run, unless it says at: the location of a declaration, field, case or parameter. A package generator's message without at: is reported at the first declaration's attribute.

Each file goes in a module: the module of the declaration that produced it by default; for a package generator, the first declaration's module, or with none, that of the package's first library file (or first binary). inModule: names another module, which must be one the package declares. The compiler starts each file with the module's module line and the imports of the declaration's file, so a generator writes only declarations and any imports of its own. A generated file may not declare a module itself.

A generated file is written to target/generated/<package>/<generator>/<file>, and its diagnostics point there, so your editor and debugger can open it. It is rewritten on every build, so editing it changes nothing, and a file the generators no longer write is removed. Two runs of one generator may not write the same file name, and names may not contain / or .. and must end in .sb (S3234).

The Rules#

A generator must give the same output for the same input on every machine. The same rules that keep a package manifest deterministic apply:

  • No effects. Nothing that reads, writes or waits: no Runtime, print, Task or Region. A generator may import only Sable.Generators, Sable.Text, Sable.Collections and Sable.Math, and the only files it sees are its package's listed inputs.
  • No conditional compilation. No #if in a generator file. Code that depends on the platform belongs in the generated output, behind its own #if.
  • Bounded. Each run is limited in steps. A generator that loops forever stops with S3231 at the attribute that started it.
  • Total. A trap, such as an index out of range or a failed !, is S3231 at the attribute, with the trap's message. Other declarations' runs still go ahead.
  • Additive. Generated files are compiled, but the attributes in them don't trigger generators. Because one generator's output is never another's input, the order they run in cannot matter.

Breaking a rule is S3230, reported at the generator.

Note

Build scripts (build.sb) are the other way to generate code. They can run tools and read files inside a sandbox the manifest declares. A rule of thumb: code that comes from the program's declarations or from data files the package carries belongs in a generator; code that needs an external tool, such as bindings for a C header or a compiled shader, belongs in a build script.

How Generators Run#

A build parses the package's files, then runs the generators before type-checking anything:

  1. Find the generators visible to each package.
  2. Compile each generator program, once per program text. The compiled code stays in memory for the life of the process.
  3. Bind the package's declarations, without their bodies, to resolve the types generators are given.
  4. Give each generator the declarations it answers to: one run per declaration for a declaration generator, one per package for a package generator.
  5. Parse what comes back, with the package's features, add the files after the package's own, and compile the whole program.

A run is keyed by the generator program's text, the toolchain and the run's input, and its result is kept. Editing a declaration re-runs the declaration generators for that declaration and the package generators whose input includes it. Editing a function body re-runs nothing.

Generators run in the interpreter, which is slower than compiled code but affects only the build: the code they write is compiled and optimised like any other, so the program is as fast as if you had written it by hand. Interpreting is also what enforces the rules, since the interpreter gives a generator only what they allow. A dependency's generator cannot touch the machine it runs on.

A loose file run with sable run file.sb has no package, so it gets no generators except the standard library's.

Generators in the Editor#

The language server runs generators just as sable check does, using the same cache, so typing inside a function body never runs one. It runs your dependencies' generators on their files as they are in the editor, so a change to a dependency shows up in the packages that use it without a reload. Go-to-definition on a generated member opens its file under target/generated/, and a generator's message appears where it points, in the file you're editing.

The generators/ directory is a project of its own in the editor: its files are checked against the rules as you type.

Testing a Generator#

A generator is tested with snapshots. Each directory under generators/tests/ is one case:

json/generators/tests/nested-types/    model.sb                       the source the generators run over    inputs/schema.json             inputs, for package generators (optional)    expected/json/User.json.sb     each file the generators write    expected/diagnostics.txt       each message they report (optional)

sable test runs the package's generators over each case, as though the case's .sb files were a package, and compares what they write and report with expected/. A difference fails the test and shows both versions. sable test --bless writes expected/ from what the generators produce, to start a new case or to accept a change once you've read the diff.

The case's files are compiled too, with the generated code. Otherwise a generator could write code that doesn't compile and still pass its snapshot. A case that is meant not to compile, because it tests a generator's error, says so with an expected/diagnostics.txt containing that error.

Generator Diagnostics#

Code Meaning
S3230 A generator breaks a rule: an import or call it may not make, a wrong signature, or a name already taken
S3231 A generator trapped or ran out of steps
S3232 A generator reported an error with output.error
S3233 A generator reported a warning with output.warning
S3234 A generator's output is not a file it may write: a bad name, a name used twice, a module line, or a module the package doesn't declare

The Standard Library's Generators#

Some standard library modules come with generators of their own, embedded in the compiler. They run for every package with a file that imports the module, and their attributes are known in files that do.

Attribute Module What it writes
@injectable Sable.DependencyInjection a factory for a class, struct or actor from its initialiser (the one marked @inject, if there are several); with a lifetime, its registration. Reads @keyed and @inject.
@container Sable.DependencyInjection a provider and scope for a dependency-injection container, with the whole graph checked at compile time. Reads @include, @singleton, @scoped, @transient and @keyed.
@syntax Sable.Syntax from a union describing a language's syntax: a kind enum, typed views of each node, builders and a visitor. Reads @base, @category, @kinds and @trivia.
@mockable Sable.Testing from a protocol, a Mock<Name> class for tests

A container, for example, is checked as the program compiles: a missing service, a scoped service inside a singleton, or a cycle without a Lazy in it is an error that names the path to it.

Sable
import Sable.DependencyInjection@injectable(.Scoped, as: OrderRepository.self)final class SqlOrderRepository: OrderRepository {    init(database: Database) {        // ...    }}@containerstruct AppServices {    @singleton fn clock() -> any Clock {        return SystemClock()    }}

And @mockable on a protocol gives you a mock to stub and verify, covered in Documentation and Testing:

Sable
import Sable.Testing@mockableprotocol PaymentGateway {    fn charge(amount: Int, to card: String) throws(PaymentError) -> Receipt}@testfn checkoutCharges() {    let gateway = MockPaymentGateway()    gateway.on.charge().returns(Receipt(id: 1))    // ...}

Why Generators and Not Macros#

Generators cover what macros are usually used for, without their costs:

  • The grammar stays fixed. There is no quoting or splicing syntax, and no tool has to expand anything before it can read a file. The formatter, the language server and you all see plain Sable.
  • No hygiene problem. Generated code is a separate file, compiled under the same name rules as any other, so a name it introduces can't capture one at your call site.
  • What you read is what runs. A generated file is on disk; you can step through it, and its errors point at its own lines.
  • Incremental by design. A generator's input is data about one declaration (or a known set), so its result can be cached. A macro sees arbitrary tokens, so it can't be.

What a macro can do and a generator can't is change existing code: rewrite a function body, or add new syntax. That is deliberate. A generator also can't add stored fields to a type, since it writes extensions and an extension can't either.

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.