Contents Open

DocsLanguage Guide

Compile-Time Evaluation

Constants, const functions, comptime blocks and conditional compilation.

Some values are known before a program ever runs: the size of a lookup table, a constant derived from other constants, whether the target is 64-bit. Sable lets you compute those values while the program is compiled, using ordinary Sable code, and lets you leave whole stretches of source out of a build depending on the platform or the build's settings.

There are two separate mechanisms here, and it helps to keep them apart. Compile-time evaluation (const, const fn, const init and comptime) runs real Sable code in the compiler's interpreter after the program has been parsed and type-checked. Conditional compilation (#if and its friends) happens much earlier, while the file is being read, and decides which text is parsed at all.

Constants#

A const declares a constant whose value the compiler works out while it compiles the program:

Sable
const Pi: F64 = 3.14159265358979const SecondsPerDay = 24 * 60 * 60const MaxConnections = 64

You met let and static let in The Basics. A let at module level is given its value once, as the program starts. A const is different: it has no storage at all. The compiler computes its value and then writes that value, as a literal, wherever the constant is read. Reading SecondsPerDay costs exactly what writing 86400 would.

Sable
@mainfn main() {    print(SecondsPerDay * 7)}
604800

Leaving the type out#

As with let, you may leave a constant's type out and have it inferred, but only when the value is one of these:

  • a literal (64, "https", true),
  • another constant,
  • a call,
  • or arithmetic on any of those.
Sable
const Width = 80                  // Int, from the literalconst Height = Width / 2          // Int, from another constantconst Area = Width * Height       // Int, from arithmetic on constants

When the value is something else, write the type.

What a constant can hold#

A constant's value can be anything the interpreter can compute: a number, a string, a tuple or struct of them, an enum case, an array. The compiler writes each one where it is read, with two practical exceptions:

  • An array with a great many elements is written once, into a global that is read where the constant is used, so a large table isn't copied into every function that looks at it.
  • A value that no literal can express, such as an object, is kept in a global that is set as the program starts, from the same code that computed it at compile time.

Either way, you write the constant the same way, and you never pay for computing it again.

Constants may also be members of a type. The standard library's Platform struct, for example, has const members that describe the target (more on those below):

Sable
public struct Platform {    public const pointerWidth: Int = 64    // ...}

Constants that need each other#

A constant may read any other constant, in any file of the program; the compiler computes the one being read first. A constant that needs itself, directly or through others, has no value to give, and is an error (S3221):

Sable
const Width: Int = Height + 1const Height: Int = Width + 1     // error: each needs the other

Constant Functions#

A constant's value is often more than a single expression. You can write a function that computes it, and mark the function const fn so that the compiler is allowed to run it:

Sable
const fn factorial(_ n: Int) -> Int => n <= 1 ? 1 : n * factorial(n - 1)const TenFactorial = factorial(10)

TenFactorial is computed while compiling. The program contains the number 3628800, not a call to factorial.

A const fn body can do most of what an ordinary body can: declare locals, branch, loop, allocate, build arrays and call other const fns. Here is one that builds a table of squares:

Sable
const fn squares(upTo limit: Int) -> Int[>..] {    var table: Int[>..] = []    var i = 0    while i <= limit {        table.append(i * i)        i += 1    }    return table}const SquareTable = squares(upTo: 100)

A const fn is still an ordinary function too. You can call it while the program runs, with values that are only known then, and it runs as any other function does:

Sable
fn describe(_ n: Int) -> String {    return "\(n)! = \(factorial(n))"     // called at run time}

const before fn works on methods as well, including static ones (static const fn), and a const fn may be declared inside another function's body.

Constant initialisers#

A type whose values you want to build at compile time needs a const init. This is how the standard library's frozen collections, from Arrays and Collections, can be constants: FrozenSet and FrozenDictionary have const initialisers that do all of their hashing work in the compiler.

Sable
import Sable.Collectionsconst Reserved = FrozenSet<String>(["con", "prn", "aux", "nul"])const Ports = FrozenDictionary<String, Int>([("http", 80), ("https", 443), ("ssh", 22)])@mainfn main() {    print(Reserved.contains("aux"))    print(Ports["https"] ?? 0)}
true443

Your own types can do the same:

Sable
struct Rgb {    var red: U8    var green: U8    var blue: U8    const init(hex: Int) {        red = U8((hex >> 16) & 0xFF)        green = U8((hex >> 8) & 0xFF)        blue = U8(hex & 0xFF)    }}const Midnight = Rgb(hex: 0x1A1A2E)

A memberwise initialiser, the one the compiler writes for a struct (see Structures and Classes), may always be called at compile time; you don't need to mark anything.

What Compile-Time Code May Call#

Code that runs in the compiler has to mean the same thing on every machine that compiles the program, and must not do anything a build shouldn't. So a constant's value, a const fn's body and a comptime block may only call:

  • another const fn or const init,
  • something the compiler wrote, such as a memberwise initialiser or a derived ==,
  • or a member of Sable.Core that neither reads, writes nor waits.

Anything else is an error where it is called (S3220). In practice that rules out unsafe, await, print, file and network access, and reading a global whose value is only set when the program runs (a static let or a module-level var). Other constants are fine.

Sable
fn square(_ n: Int) -> Int => n * nconst Area: Int = square(4)        // error: 'square' is not a const fn (S3220)

The fix is usually just to mark the function const fn.

Note

These rules are checked as the code is type-checked, so sable check and your editor report them. Whether the value can then actually be computed (it might divide by zero) is only found out by computing it.

When Compile-Time Code Fails#

A trap that would stop a running program instead stops the compile, at the constant or block where it happened:

  • Arithmetic that overflows or divides by zero, whether in the constant's own expression or in a const fn it calls, is S3201.
  • Any other trap, and a computation that needs itself, is S3221.
Sable
const Limit: Int = 9223372036854775807 + 1    // error: overflows Int (S3201)

Without this, the overflow would trap the moment the program started. Here you find out while building.

The step limit#

The interpreter counts the steps it takes. A computation that runs past the limit (twenty million steps in the current compiler: enough for any table a program would reasonably build) is stopped and reported as S3221. This is what keeps a const fn with a loop that never ends from hanging your build.

Stopping the compile on purpose#

compileError("...") stops the compile with your message, at the place it is called, when a constant's computation or a comptime block reaches it (S3222). It returns Never, so it can stand anywhere a value is expected:

Sable
const fn checkedPercent(_ value: Int) -> Int {    if value < 0 || value > 100 {        compileError("a percentage must be between 0 and 100")    }    return value}const Threshold = checkedPercent(85)     // fineconst Broken = checkedPercent(150)       // error: a percentage must be between 0 and 100

The message must be a string literal. If a const fn that contains compileError is called while the program runs and reaches it, it stops the program, as fatalError would (see Error Handling).

comptime Blocks#

A comptime block is code that runs once, while compiling, and leaves no code behind in the program. You use one to check something about the build:

Sable
const Workers: Int = 4comptime {    if Workers < 1 {        compileError("Workers must be at least 1")    }}

A comptime block may be written at the top level of a file, as above, or inside a function body. Inside a body it still runs while compiling, which is before the function is ever called, so it cannot see the function's parameters, its locals or self. It can see constants and declare locals of its own:

Sable
fn addressBits() -> Int {    comptime {        if Platform.pointerWidth != 64 {            compileError("this code assumes 64-bit pointers")        }    }    return 64}

The same rules apply in a comptime block as in a const fn: only constant-safe calls (S3220), and a trap is a compile error.

The Target as Constants#

Sable.Core's Platform describes the target the program is being compiled for, as constants, so compile-time code can test them:

Constant Type Value
Platform.os String "macos", "linux", "windows" or "wasi"
Platform.arch String "arm64", "x86_64" or "wasm32"
Platform.pointerWidth Int 64, or 32 on wasm32
Platform.vectorBytes Int how many bytes a vector register holds (16)
Platform.hasByteLookup Bool whether the target has a sixteen-byte table lookup instruction (arm64 does)

These are the target's, not the machine running the compiler's: cross-compiling for Linux from a Mac gives "linux".

Sable
comptime {    if Platform.os == "wasi" && Platform.pointerWidth != 32 {        compileError("unexpected WASI target")    }}

Platform also has members that are asked of the system as the program runs, such as Platform.processorCount and Platform.isAtLeast(macOS: 13). Those are ordinary properties and functions, not constants, so compile-time code can't call them.

Conditional Compilation#

#if leaves parts of a file out of the build. It works on the source text before anything else happens: the region that isn't taken is never parsed or type-checked, so it may refer to functions that don't exist on this platform.

Sable
fn configurePath() -> String {    #if os(windows)    return "C:\\ProgramData\\inventory"    #elseif os(macos)    return "/Library/Application Support/inventory"    #else    return "/var/lib/inventory"    #endif}

The directives are #if, #elseif, #else and #endif. Each must be the first thing on its line. You can use them at the top level of a file, among a type's members, and between statements in a body.

Conditions#

Because a condition is evaluated before any type checking exists, it is a small language of its own. It may contain only:

Form True when
DEBUG the build is unoptimised, or the profile asks for debug assertions
RELEASE the build is optimised, and the profile does not ask for debug assertions
an identifier that symbol is defined for this build; an unknown one is simply false
true, false always, never
os(name) the target's operating system is macos, linux, windows or wasi
arch(name) the target's architecture is arm64, x86_64 or wasm32
feature(name) the package is built with that feature enabled
!, &&, ||, ( ) combinations of the above
Sable
#if os(macos) && arch(arm64)let backend = "metal"#elseif feature(vulkan) || os(linux)let backend = "vulkan"#elselet backend = "software"#endif

feature(...) tests the features declared in the package's manifest (see Modules and Access Control). Each file is parsed with its own package's features, so a dependency's #if feature(png) means the dependency's feature, not yours.

A condition that uses anything else, such as a comparison or a function call, is malformed: the compiler reports it and treats the region as not taken, rather than losing track of the rest of the file.

DEBUG and RELEASE#

Exactly one of DEBUG and RELEASE is defined in any build, never both. DEBUG is defined in an unoptimised build (the default for sable build and sable run) and by sable check; RELEASE in an optimised one (--release).

Sable
fn verboseLogging() -> Bool {    #if DEBUG    return true    #elseif RELEASE    return false    #endif}

A package's build profile can choose for itself with the debug-assertions setting, whatever its optimisation level: a profile that is optimised but sets debug-assertions builds with DEBUG. The choice applies to every package's files in the build, the standard library's included, which is how assert (from The Basics) knows whether to check.

Disabled regions are kept#

A region that isn't taken is not thrown away. The compiler keeps its text in the syntax tree as disabled text, so the formatter leaves it exactly as you wrote it and your editor can show it greyed out and offer to switch configurations. Two parses of the same file under different settings give different trees, and both turn back into the same text.

This is one reason to prefer #if to commenting code out: sable fmt won't damage it, and it reappears the moment the condition is true.

#error and #warning#

#error reports its message as a compile error, and #warning as a warning, wherever they are compiled. They are most useful inside a conditional region, where they report nothing unless that region is taken:

Sable
#if os(wasi)#error("the inventory server needs threads, which WASI does not have")#endif#if !feature(tls)#warning("built without TLS: connections are unencrypted")#endif

The message may be written in parentheses or not (#error "not finished"). #error is S0029 and #warning S0030. Any other #name at the start of a line is an unknown directive (S0025); an #endif with no #if is S0026, and an #if the file never closes is S0027.

Tip

Use #if and #error for what you can tell from the configuration alone (platform, feature, debug or release). Use comptime and compileError for checks on values the program computes, such as constants.

Where Am I? Source Location Builtins#

Six names starting with # are not directives but expressions, and may be written anywhere an expression may:

Builtin Type Value
#file String the file it is written in
#line Int the line it is written on
#column Int the column it is written at
#function String the function it is written in
#module String the module it is written in
#expression (see below) how the call's first argument was written
Sable
fn loadInventory() {    print("\(#module).\(#function) at \(#file):\(#line)")}

Their most useful property shows up when one is a parameter's default value. Then it takes the place of the call, not of the function's declaration. That is how assert and precondition report the line that failed rather than a line inside the standard library:

Sable
fn log(_ message: String, file: String = #file, line: Int = #line) {    print("[\(file):\(line)] \(message)")}log("restocking")        // prints this call's own file and line

#expression#

#expression is only allowed as a parameter's default value, and not the first parameter's (S3517). The parameter is given how the call's first argument was written, along with the value of each part of it as it was worked out. Its type is a class with a static fn begin() that makes an empty one and a fn note<T>(_ text: String, _ value: T) -> T that records a part; the standard one is Sable.Testing's CapturedExpression.

This is how a test's expect(items.count == 3) can report not just that the condition was false but that items.count was 2. Documentation and Testing shows it in use.

Why Sable Has No Macros#

If you come from C, Rust or Swift, you may be looking for macros. Sable has none, and this is a decision rather than something not yet built. What macros are typically used for is covered by other tools:

  • Computing values at compile time: const, const fn and comptime, in this chapter.
  • Writing the standard conformances such as ==, hashing and serialisation: @derive.
  • Generating code from declarations: source generators, which are Sable functions that read declarations and write new source files.

The last two are the subject of the next chapter, Derivation and Source Generators.

The cost macros would bring is real. A macro system needs quoting and splicing syntax in the grammar, and every tool that reads Sable would have to expand macros before it could understand a file. Macros need hygiene rules so that names they introduce don't capture names at the call site. And what a macro expands to is only visible through a tool. Generated code, by contrast, is a plain Sable file on disk: you can read it, step through it, and its errors point at its own lines.

What generators can't do is rewrite code you wrote, or add new syntax. That is the point. Conditional compilation, likewise, is deliberately limited to choosing which text is compiled: an #if condition can't compute anything, and there is no #define.

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.