Contents Open

DocsLanguage Reference

Lexical Structure

Source text, identifiers, the newline rule, keywords, literals, operators and directives.

The lexical structure of Sable describes which sequences of characters form valid tokens: the identifiers, keywords, literals, operators and punctuation that the grammar is built from, and the trivia — whitespace, comments, disabled code — that lies between them. This chapter states every lexical rule. The Language Guide introduces the same material gradually, starting in The Basics and Strings and Characters.

Sable's lexer is unusual in two ways. It keeps every character of the source, attached to tokens as trivia, so that the formatter and the IDE work on the same tree the compiler does. And it decides where statements end: Sable has no required semicolons, and the newline rule below says exactly when a line break ends a statement.

Source text#

A Sable source file has the extension .sb (an interface file, .sbi). It is UTF-8 text with no byte order mark: a BOM at the start of a file is an error (S0018), not something skipped.

Lines may end in LF, CRLF or CR. The lexer normalises all three to LF for the purposes of the language, and keeps the original in trivia so that a file is reproduced exactly.

Trivia#

Everything in a file that is not a token is trivia, and trivia is never thrown away. It is attached to a token:

  • Leading trivia attaches to the token that follows it.
  • Trailing trivia, up to and including the end of the line, attaches to the token before it.

Concatenating every token with its trivia reproduces the source file byte for byte; the compiler tests this invariant.

Trivia kind What it is
Whitespace Spaces and tabs
NewLine A line terminator
LineComment // … to the end of the line
BlockComment /* … */, which nests
DocComment /// …, /** … */ and //! …
DisabledText The lines of an #if region that is not taken
Directive The line of a compiler directive itself
ShebangLine A #! line at the very start of a file

Identifiers#

EBNF
Identifier     = IdentStart { IdentContinue }IdentStart     = Letter | "_"                      (* Unicode XID_Start + '_' *)IdentContinue  = Letter | Digit | "_"              (* Unicode XID_Continue    *)

An identifier starts with a letter (Unicode XID_Start) or an underscore, and continues with letters, digits (XID_Continue) and underscores. Identifiers are compared after NFC normalisation, so two spellings of the same accented letter name the same thing.

_ on its own is not an identifier: it is the wildcard, in patterns, parameter labels and _ =. A leading underscore on a longer name is only a convention for "unused" and has no meaning to the compiler.

Sable
let temperature = 21let café = "open"let _scratch = 0

Escaped identifiers#

To use a keyword as an identifier, enclose it in backticks:

Sable
let `class` = "Mammalia"print(`class`)

An escaped identifier must be closed on the line (S0019) and may not be empty (S0020). After a ., no escaping is needed: any keyword may name a member there (see Expressions).

Implicit closure parameters#

Inside a closure that declares no parameters, $0, $1, … name its parameters by position. The $ token exists only for this.

Sable
let active = users.filter { $0.isActive }

The newline rule#

Sable does not require semicolons. A newline ends a statement unless the line cannot yet be a complete statement. The lexer decides this from the tokens on either side of the line break. A newline is not a statement terminator when any of the following holds.

  1. The line ends on a token that needs more. The last token on the line is one of

    ( [ { , . : = => -> | & && || + - * / % << == != < <= >= ?? as is where

    or any assignment operator (+=, ??=, &+=, …), or a keyword that must be followed by more.

  2. The next line starts with a token that continues. The first token on the next line is one of

    . ?. ? : => -> , ) ] else catch where

    or any binary operator — or while directly after a }, which continues repeat { … }. A while anywhere else starts a loop of its own.

  3. The lexer is inside unbalanced ( or [. Newlines inside parentheses and brackets never end a statement. A { inside them opens a body of statements, in which newlines end statements again until its }.

The tokens that may end a statement are identifiers, literals, ), ], }, ?, !, >, >>, ..., the keywords self, Self, super, true, false, none, get and set, and the jump keywords below.

Sable
let total = price    + shipping                        // continues: the line starts with '+'let names = people    .filter { $0.isActive }           // continues: the line starts with '.'    .map { $0.name }let label = isReady    ? "ready"                         // a conditional may break before '?' and ':'    : "waiting"

Jump keywords always terminate#

return, break, continue, throw and fallthrough end their statement at the newline, always. A value they take must be on the same line:

Sable
return    computeTotal()      // not returned: a separate statement after a bare 'return'

This rule is the guard against JavaScript's automatic-semicolon hazard: a bare return can never silently swallow the next line.

Consequences#

Three consequences of the rule are deliberate:

  • } is not a continuation token. A closing brace ends the statement before it, and can itself end a statement: fn f() { } followed by a newline terminates.
  • { must be on the same line as its header. A brace at the start of a line would be ambiguous with a trailing closure, so Sable takes Go's rule rather than Swift's and rejects the Allman style, with a diagnostic that says so (S1011).
  • >, >> and ? can end a statement, so that var xs: List<Int>, List<List<Int>> and var x: Int? terminate at the newline. The price is that a multi-line expression may not break after >, >> or ?; break before the operator, or parenthesise.

Semicolons#

A ; may be written to put several statements on one line. Inside a type body written on one line, , or ; separates members. The formatter removes semicolons that are redundant.

Sable
var x = 0; x += 1struct Vec3 { x: F32, y: F32, z: F32 }

Keywords#

Reserved keywords#

These words are reserved everywhere and cannot be used as identifiers unless escaped with backticks:

abstract     actor        alias        any          as           asyncawait        borrowing    break        case         catch        classconst        consuming    continue     default      defer        deinitdo           else         enum         extension    fallthrough  falsefinal        fn           for          guard        if           importin           init         inout        internal     is           lazylet          match        module       move         mutating     nonenonisolated  nonmutating  open         operator     out          overridepackage      postfix      prefix       private      protocol     publicref          region       repeat       required     rethrows     returnsealed       self         Self         some         static       structsubscript    super        switch       throw        throws       truetry          typealias    union        unowned      unsafe       usingvar          weak         where        while        yield

After a ., any keyword may still name a member: super.init(), T.self, options.default.

Words reserved to point you elsewhere#

Three reserved words declare nothing. They exist so that code written in another language's spelling gets a precise error:

Word Diagnostic Write instead
typealias S1012 alias, which also gives an associatedtype its type in a conformer
ref S1013 a reference type after the type: a: Node&, -> Node&
borrowing S1013 likewise T&; classes and @noncopy values are already passed by reference

nonmutating is reserved and accepted as a modifier by the parser, but has no effect today.

Contextual keywords#

These are keywords only in their syntactic position, and ordinary identifiers everywhere else:

Word Where it is a keyword
associatedtype A protocol member
convenience A modifier on init
get, set Accessor blocks
willSet, didSet Property observers
comptime Before a block: comptime { … }
unchecked Before as: x unchecked as I32

newValue and oldValue are not keywords at all: they are ordinary identifiers that set, willSet and didSet bodies have implicitly bound.

Reserved for future use#

These identifiers are reserved so that a future version can give them meaning:

trait  impl  become  effect  handler

Literals#

A literal is the source spelling of a value. Literals have no fixed type of their own: each takes the type its context asks for, and otherwise a default. Sable has no ExpressibleBy… protocols; which types a literal can be is decided by the compiler. How literals combine into expressions — arrays, dictionaries, tuples, records — is in Expressions.

Integer literals#

EBNF
IntegerLiteral = DecimalLit | HexLit | OctalLit | BinaryLitDecimalLit     = Digit { Digit | "_" }HexLit         = "0x" HexDigit { HexDigit | "_" }OctalLit       = "0o" OctalDigit { OctalDigit | "_" }BinaryLit      = "0b" BinDigit { BinDigit | "_" }
Sable
let decimal = 1_000_000let hex = 0xFFlet octal = 0o755let binary = 0b1010_0110
  • _ separates digits. It may not lead (S0012) or trail (S0013) the digits.
  • A digit the base does not have is an error (S0022), as is a prefix with no digits (S0011).
  • The default type is Int. Context changes it: let x: U8 = 200.
  • A literal that does not fit the type it is given is a compile-time error, never a wrap (a literal too large even to lex is S0014).
  • There are no type suffixes. Write a type annotation or as: let mask: U32 = 0xFF, 0xFF as U32.

Floating-point literals#

EBNF
FloatLiteral   = DecimalLit "." DecimalLit [ Exponent ]               | DecimalLit Exponent               | HexLit "." HexDigits "p" [ Sign ] DecimalLitExponent       = ( "e" | "E" ) [ "+" | "-" ] DecimalLit
Sable
let pi = 3.14159let tiny = 1e-9let twelve = 0x1.8p3      // 1.5 × 2³
  • The default type is F64.
  • A digit is required on both sides of the point: 1. and .5 are not literals. This keeps 1..<5 a range and pair.0 a tuple element.
  • A hexadecimal float needs its p exponent (S0016).

Character literals#

EBNF
CharLiteral = "'" ( SourceChar | EscapeSeq ) "'"

A Char is one Unicode scalar value — not a UTF-16 code unit and not a grapheme cluster. '\u{1F600}' is a single Char. An empty character literal is S0006; more than one scalar is S0007.

Sable
let letter = 'a'let newline = '\n'let grin = '\u{1F600}'

String literals#

There are three forms of string literal, all of type String (UTF-8).

Sable
let simple = "with \n escapes and \(interpolation)"let poem = """    multi-line: the closing delimiter's indentation    is stripped from every line    """let pattern = #"raw: \n is two characters, " needs no escape"#let nested = ##"raw with more hashes, so "# can appear"##
  • Single-line, "…": escapes and interpolation; must close on its line (S0003).
  • Multi-line, """…""": the opening and closing delimiters are on lines of their own (S0023). The indentation of the closing delimiter is removed from every line, and a line indented less than it is an error (S0024). A backslash at the end of a line joins it to the next.
  • Raw, #"…"#: no escapes and no interpolation. Any number of # may be used, and the string ends only at a " followed by as many # (S0005 if it never does).

The escape sequences are:

Escape Meaning
\0 Null
\\ Backslash
\t \n \r Tab, line feed, carriage return
\" \' Double and single quote
\u{…} The Unicode scalar with that hexadecimal value, 1–8 digits
\(expr) Interpolation

An unknown escape is S0008; a malformed \u{…} is S0009, and one that is not a scalar value S0010.

Interpolation#

\(expr) in a single-line or multi-line string inserts the value of expr. Interpolations nest arbitrarily — a string inside a hole may itself contain holes — and the whole string is one token. The parser then takes it apart so that each hole is an ordinary expression in the tree. A colon after the hole's expression starts a format spec, which runs as raw text to the hole's closing parenthesis: "\(n:#06x)". The spec's grammar is in Expressions, and the guide's Strings and Characters teaches it. An unclosed hole is S0021.

Boolean and none literals#

true and false are the Bool literals. none is the empty optional, valid only where an optional is expected: it is Optional.None.

Collection literals#

Array, dictionary, tuple and record literals are not tokens but expressions; see Expressions. Note that [:] lexes as three tokens, [, : and ], and is the empty dictionary in expression position.

Operators and punctuation#

( ) [ ] { }. ?. .. ..< ..., : ; ?-> =>= += -= *= /= %= &= |= ^= <<= >>= ??= &+= &-= &*=+ - * / %   &+ &- &*& | ^ ~ << >>== != === !== < <= > >=&& || !?? @ # _ \ $

The lexer takes the longest token it can (..< before .., &+= before &+). The meanings of the operators, and their precedence, are in Expressions. Sable has no custom operators: this list is complete.

How & is read#

& has three meanings, resolved by position:

Position Meaning Example
Between two expressions Bitwise and flags & mask
Before an expression Address-of: a reference, or an argument the call may write inc(&n), let r = &xs[0]
After a type Reference type fn area(_ r: Rect&)

Between two types, in a constraint or a type, & composes protocols: some Hashable & Debug.

& immediately followed by +, - or * is always a wrapping operator — &+, &-, &*, and with = after, &+=, &-=, &*=. So a&-b is a &- b, and a bitwise and with a negated operand needs a space: a & -b.

How < and > are read#

< and > are both comparison operators and generic brackets. The parser decides: when < follows a type-position identifier with no whitespace between, it scans ahead for a matching > that does not cross a statement terminator, and if it finds one, reads generic arguments. This is C#'s rule and it shares C#'s rare pathological cases; parenthesise to force a comparison.

Sable
let cache = Cache<String, Int>()    // generic argumentslet smaller = a < b                 // comparison

How ^ is read#

Between two expressions, ^ is exclusive or. As a prefix, ^n is a position counted from the end of a collection (a FromEnd): xs[^1] is the last element. Prefix ^ means nothing else.

How ? and ! are read#

After an expression with no space before it, ? begins optional chaining (a?.b, f?(), xs?[0]); with a space before it, it is the conditional operator (n > 1 ? [1] : [2]). After a type, ? makes it optional. ! after an expression force-unwraps, before one negates; after try with nothing between them, try! is a single form (try !f() negates).

Comments#

Sable
// a line comment/* a block comment /* nested */ still in the block *//// a doc comment for the declaration that follows/** a block doc comment *///! a module-level doc comment, first in a file

Block comments nest, so commenting out code that contains a block comment works. An unterminated block comment is reported at its opening /* (S0002), not at the end of the file.

Doc comments are Markdown. sable doc renders them, and fenced sable code blocks inside them are compiled and run as tests by sable test; see Documentation and Testing.

Compiler directives#

#if  #elseif  #else  #endif#error  #warning

A directive must be the first thing on its line; the directive's line is Directive trivia. Any other #name at the start of a line is reported as an unknown directive (S0025).

Conditional compilation#

Sable
#if DEBUG    log.verbose = true#elseif RELEASE    log.verbose = false#endif#if os(macos) && arch(arm64)    useMetal()#else    useVulkan()#endif

The condition after #if and #elseif is evaluated before any semantic analysis, so it may use only:

Form True when
an identifier that symbol is defined for this build (DEBUG, RELEASE, or a symbol the build defines)
true, false always, never
os(name) the target's OS is macos, linux, windows or wasi
arch(name) the target's architecture is arm64, x86_64 or wasm32
feature(name) the package feature is enabled
!, &&, ||, ( ) combinations of the above

DEBUG is defined in an unoptimised build (and by sable check), RELEASE in an optimised one, never both. A malformed condition disables its region and reports S0028 rather than derailing the parse. An #endif, #else or #elseif without an #if is S0026; an #if never closed is S0027.

The lines of a region not taken are lexed as DisabledText trivia: not parsed, but kept, so that the formatter preserves them and an editor can switch configurations. Which symbols are defined is part of the parse configuration, so one file can produce different trees; both round-trip. A conditional region may appear at the top level, among statements, and inside a type body. The guide covers this in Compile-Time Evaluation.

Diagnostics#

#error and #warning report a message of their own, written #error("message") or #error "message". They fire only in a region that is taken: S0029 for an error, S0030 for a warning.

Sable
#if !os(macos) && !os(linux)#error("this package supports macOS and Linux only")#endif

Builtin literals#

Six #names are expressions rather than directives, read as such wherever they appear (that a directive must start a line is what tells them apart):

Builtin Value
#file The current file's name
#line The current line
#column The current column
#function The enclosing function's name
#module The current module's name
#expression As a parameter default: what the call's first argument was written as, with its parts' values

Used as a parameter's default, #file, #line, #column and #function take the place of the call, which is how assert and precondition report where they were called from. #expression is allowed only as a default, and not on the first parameter (S3517); see Error Handling.

Shebang#

A file may begin with #!… on its first line. The line is ShebangLine trivia, so a single-file script can be made executable:

Sable
#!/usr/bin/env sablemodule Scriptprint("hello")
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.