sysl

Strings

An immutable, validated []u8 — the representation, the guarantee, every form that makes new bytes, and where the allocator line falls.

A string is a three-word owning view of validated UTF-8 bytes — the same shape every slice has, with one thing added and one taken away:

ownerthe counted buffer keeping the bytes alive, or null for immortal bytes
ptrthe first byte of this string — an interior pointer into the owner’s bytes
lenthe length in bytes, not characters

Added: the bytes are guaranteed to be well-formed UTF-8. Taken away: nothing may write through it. Every rule on the arrays page about indexing, slicing, length and ownership therefore applies here too, and this page covers the two differences and what follows from them.

ptr is separate from owner because a substring must name a range inside its parent’s buffer while keeping that parent alive. Two words cannot do both: with only {ptr, len}, releasing the string has no way back to the buffer header, so either every substring copies or its lifetime goes unchecked. The third word gives O(1) substring sharing for eight bytes.

Other languages make different choices. Go’s two words work because a garbage collector owns the bytes and can find the object from an interior pointer; sysl has no collector, so two words would leave lifetime unanswered. Swift’s packed sixteen bytes hide three representations behind a discriminator, always require an allocator, and use a grapheme-cluster element type whose break tables do not belong in a kernel. Rust splits the job between a &str view and an owning String, which costs every signature a choice between two types. sysl uses one type of three words.

A string of a few bytes holds them in itself

This form is off by default, and SYSL_SHORT_STRINGS=1 turns it on for a build. It allocates less but is not yet faster on every program, so it stays a choice until it is.

With it on, a string the program makes of 15 bytes or fewer — 7 on a 32-bit machine — keeps its bytes in its own three words and costs no allocation at all. The owner word is null, as a literal’s is, so counting it costs nothing; the bytes fill the next two words but one byte; and that last byte, the top byte of the length word, holds the length with its top bit set, which no length a long string could have can reach. Every reader of a string asks that bit first, so a program sees one type:

a long stringa short string
word 0the owner, or nullnull
word 1the first byte’s addressbytes 0 to 7 (0 to 3 on 32 bits)
word 2the lengthbytes 8 to 14 (4 to 6), then 0x80 + the length in the top byte

The short form is what a copy, from_utf8, a concatenation, an interpolation, a builder’s finish, a rendered number or a character comes to when its bytes fit; past that it is a counted buffer as before. A literal is never short — its bytes are already in read-only data, with nothing to save — and neither is the empty string, a cut of a long string (it shares its parent’s bytes) or str_view. A cut of a short string is short. Comparison, hashing, match, slicing and every library call answer exactly as they would for the long form; only the allocation counts differ.

s.bytes of a short string is a copy of the bytes in a slot of the frame, since bytes held in a value have no address of their own. A view lent to a call, indexed, iterated or held in a local costs nothing, and a later write to s never reaches it:

var s = 1234.to_string()
val b = s.bytes

s = "zz"
print(b.len, b[0], s)
4 49 zz

A view that outlives the frame — returned, stored on the heap, handed to a parameter that keeps it — is copied to the heap once, which --explain-escapes names: “is the bytes of a string that may be held in the string itself, so it is copied to the heap”. Two .bytes of one short string are two different addresses. A raw pointer into those bytes (as_ptr(s.bytes), &s.bytes[0]) cannot be given a copy that lasts — a pointer counts nothing — so one that would outlive the frame is refused: lend it at the call that reads it (f(as_ptr(s.bytes))) or copy the bytes into a Buf[u8] the caller owns.

A member marked @views(self) that takes *self reads self.bytes where the caller holds the string, with no slot and no copy, short or long: the mark already holds the view to the caller’s name and refuses a write to that name while the view is live. That is how Search reads its receiver: its members ask view_in_place, so s.index_of(…), s.starts_with(…) and the rest of a short string allocate nothing. view itself still takes the receiver by value, so it is asked of a val, a temporary or a []u8 as before.

A compiled library records which form it was built with, and a build in the other form refuses it by name rather than linking bodies that read a string’s words two ways. With the form off, the default, every string is long, byte for byte as before the form existed.

Validity

Every string is well-formed UTF-8. This matches char, which already guarantees that its value is a Unicode scalar value: a string that could hold arbitrary bytes would make decoding partial, and would give a decoder a way to produce a char that cannot exist.

The guarantee is Swift’s rather than Go’s. Go strings are arbitrary bytes that are UTF-8 by convention, so its decoder must substitute U+FFFD and advance one byte on malformed input. A sysl decoder has no repair path, because there is never anything to repair.

fromspellingbehaviour
a literal"héllo"validated while compiling
bytesfrom_utf8(b: []const u8)validates; the error names the byte offset
bytes, trustedfrom_utf8_unchecked(b)unsafe — the long name keeps every use easy to find
bytes, trusted and sharedstr_view(b: []u8)unsafe — no copy: the string sees later writes to b
a charstring(c)encodes one scalar value
import sysl.text.from_utf8

var good: [2]u8 = [0xC3, 0xA9]
var bad: [2]u8 = [0xC3, 0x28]

from_utf8(good) match
    Ok(t) -> print("ok", t.len, t)
    Err(e) -> print("bad", e.offset)

from_utf8(bad) match
    Ok(t) -> print("ok", t.len)
    Err(e) -> print("bad at", e.offset, "truncated:", e.truncated)
ok 2 é
bad at 0 truncated: false

Utf8Error carries one thing besides the offset: whether the input merely ended in the middle of a sequence. That is the only distinction a caller can act on differently — more bytes can complete an unfinished sequence but can never fix a wrong one — so it is a field rather than a list of fault names. The pair above shows the difference: C3 28 is a lead byte followed by something that is not a continuation, so no further input can make it valid.

The validator follows Unicode’s well-formedness table rather than decoding and then range-checking. In the table the lead byte fixes the legal range of the byte after it — E0 requires A0..BF, ED only 80..9F, F0 requires 90..BF, F4 only 80..8F — so an overlong encoding, a surrogate and a value past 10FFFF are all rejected at the second byte, by the same test, before any code point is assembled. Decoding first would need a separate check for each case.

from_utf8 copies rather than views. A string could share a []u8‘s owner, which would make the conversion O(1), but a slice is writable and a string is not, so a later write through the slice would change a value that had already been checked. Copying keeps the validation true afterwards, which is why from_utf8 requires an allocator.

from_utf8 is library code, not a compiler built-in. The compiler supplies exactly one primitive — str_cast, which takes a []u8 as a string without examining it — and everything on top of it is ordinary sysl in sysl.text, from_utf8_unchecked included. That primitive is the one step no sysl body could write, because every safe route to a string already carries the guarantee.

str_cast and its in-place counterpart str_alias are imported, from sysl.raw, beside ptr_cast (memory.md § Reinterpreting storage): the compiler answers them, but a file names the raw-tier forms it uses, the way it names anything else it did not declare. str_cast(b) copies the bytes into a new string; str_alias(b) lays the string over b itself, which the caller keeps unchanged and alive for as long as the string is read.

import sysl.raw.{str_alias, str_cast}

var bytes: [5]u8 = [104, 105, 33, 33, 33]

print(str_cast(bytes[0..<3]), str_alias(bytes[0..<2]))
hi! hi

The import is required. Written without it, the form is refused, and the error names the line to add:

var bytes: [3]u8 = [104, 105, 33]

print(str_cast(bytes[..]))
'str_cast' is in sysl.raw: add 'import sysl.raw.str_cast'

The unchecked conversion is imported like any other function:

import sysl.text.from_utf8_unchecked

var bytes: [3]u8 = [104, 105, 33]

print(from_utf8_unchecked(bytes))
hi!

The primitive underneath it is deliberately in the same category as a raw pointer, because breaking the UTF-8 invariant breaks char‘s invariant downstream.

A string that shares a buffer

str_view(b: []u8) -> string is the one conversion that does not copy. The string is the slice’s three words: it takes a share of the slice’s owner, exactly as s[a..b] shares a string’s, and allocates nothing. It exists for a buffer that grows in place and is read back as text at every step — an appending builder whose contents are handed out as a string each time — where from_utf8_unchecked would copy the whole of the text on every call. Go’s unsafe.String is the same operation.

It is in the unsafe tier, and the caller owes two guarantees rather than one. The bytes are valid UTF-8, as for from_utf8_unchecked; and nothing writes the bytes the string covers while the string is alive, because the rest of the language treats a string as immutable. The program below breaks the second guarantee deliberately, to show what it protects:

import sysl.text.{from_utf8_unchecked, str_view}

var store: []u8 = [0; 16]
store[0] = 104
store[1] = 105

val viewed = str_view(store[0..<2])
val copied = from_utf8_unchecked(store[0..<2])

store[1] = 97
print(viewed, copied)
ha hi

Writing past the end of the view keeps both promises, since the string’s length is the slice’s, fixed where it is made — which is exactly how a buffer grows in place.

The storage stays the compiler’s business. The string holds its share of the owner for as long as it lives, so the bytes outlive the slice and every other holder. A slice of a *T region has no owner to share, and is the programmer’s problem exactly as every *T is.

A string over an array the frame owns is a view of that array, and is followed as one. It may be read where it is made, held in a local, and handed to any function whose body only reads it — its .len, its bytes, a comparison, a search — or hands it on to one that does. The compiler reads the callee’s body to tell, as it does for a []T; so the bytes may equally arrive as a []u8 parameter and be made into a string one frame down. Nothing is allocated, which is what lets a function format into a buffer on its stack under @no_alloc:

import sysl.text.str_view

@no_alloc
shout(s: string) -> usize
    var n: usize = 0

    for c in s.bytes
        if c >= 65 && c <= 90 then n += 1

    n
end shout

@no_alloc
measure(b: []u8) -> usize = shout(str_view(b))

@no_alloc
frame() -> usize
    var text: [8]u8 = [72, 105, 32, 77, 111, 109, 0, 0]
    val s = str_view(text[0..<6])

    shout(s) + measure(text[0..<2]) + s[3..<6].len
end frame

print(frame())
6

Where the string would outlive the array, the array moves to the heap — the same promotion a returned slice gets, named by --explain-escapes at the place the string leaves: returned, stored in a field or in module storage, pushed into a buffer, captured by a closure that is returned, or handed to a function that does any of those, however many calls down. A cut of the string and its .bytes are the same view and leave the same way; a string built from it — an interpolation, a + — is a copy, and leaves on its own.

import sysl.text.str_view

var last = ""

remember(s: string) = last = s

made() -> string
    var text: [2]u8 = [111, 107]
    str_view(text[0..<2])
end made

noted()
    var text: [2]u8 = [104, 105]
    remember(str_view(text[0..<2]))
end noted

noted()
print(made(), last)
ok hi

Under @no_alloc there is nothing to move the array into, and the escape is refused where it is made:

import sysl.text.str_view

var last = ""

remember(s: string) = last = s

@no_alloc
noted()
    var text: [2]u8 = [104, 105]
    remember(str_view(text[0..<2]))
end noted

noted()
this view of 'text' is passed to 'remember', which holds on to it, so the array would move to the heap to outlive the frame

Where no body can be read, the string is taken to be kept: a call through a trait object, a &Fn or a function pointer moves the array, as does a function whose body is not part of the build.

Immortal bytes

A string literal is bytes in read-only data with no owner at all — the owner word is null, and retain and release both test for that and do nothing. As a result:

  • A literal costs no allocation and no refcount traffic. It is a constant, so it needs no instruction to build either.
  • Allocator-free code can hold, pass, compare, index and slice literals.
  • Any string derived from a literal by slicing is immortal too, because it shares the owner.
  • A module-level val holds one with no code running first. Module storage may hold a built string too, and never releases it; a literal is the case that needs no prologue at all.

A sentinel refcount in a header could express the same thing. The null owner is preferred because it is not specific to strings: it is already how a slice of static storage says “nothing to keep alive”, so immortality needs no mechanism of its own.

Shared bytes

A string crosses into an object two threads reach — a capture of a &sync Fn, a field of a &sync T — with no spelling of its own. Where the object is made, each string in it is copied once into bytes whose owner’s count is atomic, marked so by its top bit; every share of those bytes is then taken atomically, a substring’s included, on whichever thread takes it. A literal is left as it is, having no count, and so is a string already shared. The string the program held keeps its ordinary count, so code that shares nothing pays only the test of the mark on each share it takes.

struct Reg
    tag: string

val n = 4
val r: &sync Reg = Reg(s"dev$n")
val job: &sync Fn() -> string = () -> r.tag[1..<r.tag.len]

print(job(), r.tag)
ev4 dev4

Where nothing copies a string on its way to another domain it is still refused: module storage, a view of strings, a frozen buffer of them, a pointer’s pointee. The whole rule is in memory § A string crosses into a shared object.

Granularity: bytes and scalar values

A string is indexed and measured in bytes, and decoded into char — Unicode scalar values. Grapheme clusters are a library built over the scalar view, not the element type.

The reason is where the Unicode data would have to live. Grapheme breaking needs tables that do not belong in a kernel, and making the element type one that requires them would make a length O(n) and force an opaque index type on every program that only needs a byte offset. Go’s choice suits a systems language; Swift’s suits an application language.

The tables are in the standard library, and they do not change the element type. sysl.unicode carries the whole Unicode Character Database and answers grapheme breaking, case mapping, folding and normalization over a byte view. It is the library built over the scalar view this section describes, so a char remains a scalar value and s.len remains a count of bytes. A program links none of it unless it calls into it.

operationspellingcost
byte lengths.lenO(1)
byte at an indexs[i] -> u8O(1), bounds-checked
substrings[a..b] -> stringO(1), shares; bounds-checked and boundary-checked
bytess.bytes -> []const u8O(1) view
scalar valuess.charsO(1) per step, total — no replacement characters
grapheme clusterssysl.unicode.graphemes_of(s.bytes)O(1) per step, allocates nothing
copy outs.copy()O(n), allocates; releases the parent
concatenationa + bO(n), allocates
repeated appendstr_builder()amortized
var s = "héllo"

print(s.len, s[0], s[1], s[2])

var count = 0

for c in s.chars do count += 1

print(count, s.bytes.len)
6 104 195 169
5 6

The string is six bytes and five characters: the é occupies the two bytes 195 169, at indexes 1 and 2.

Indexing gives a byte, and there is no way to write one

var s = "hello"

s[0] = 65
a string is immutable, so its bytes have no address to write through

Writing through s.bytes is refused too, with a diagnostic that says why:

var s = "hello"

s.bytes[0] = 65
'bytes' views the string's own storage rather than a copy of it — so writing through one is writing the string

The bytes are a []const u8, the type that records exactly this. To modify them, copy them into a []u8 of your own first.

Slicing is boundary-checked

var s = "héllo"

print(s[0..<1], s[1..<3], s[3..])
h é llo

s[a..b] must land on scalar-value boundaries at both ends. Landing mid-character traps, in the same runtime-safety category as a bounds check and a failed char(u):

var s = "héllo"

print(s[0..<2])

Byte 2 is the second half of the é, so that program stops there — no message, no unwinding.

Go permits the mid-character slice and so lets a program build an invalid string. The validity guarantee rules that out here, for a string that arrived through from_utf8 exactly as for a literal: validating input is only useful if nothing downstream can undo it.

Walking the characters

s.chars is a cursor — a value implementing Iterate with char for its Item — and it is the one row of the table above that is not a value or a view. Every other row yields a value; this one yields a sequence, produced by decoding, so something has to carry a position and answer “the next one”.

The cursor validates nothing. A string is well-formed by construction, so the decoding reads the length off the lead byte and takes the continuation bytes as given — which is why the cost is O(1) per step and why there are no replacement characters to hand back.

A for walks a copy of a cursor, so a loop cannot be asked afterwards where it got to. A program that needs to know drives the cursor itself, and gets three more answers, all by value, so asking consumes nothing:

var s = "héllo"
var cur = s.chars

print(cur.offset, cur.count(), cur.peek().unwrap())

cur.next()

print(cur.offset, cur.peek().unwrap())
0 5 h
1 é

This is the shape a lexer needs: a reader with only “the next one” would have to index bytes by hand and decode a second time to find out where it is.

char_indices is the paired walk, yielding each character with the offset of its first byte, under the name Rust uses for the same operation. Reporting the first byte makes the offset directly usable: a slice built from two reported offsets lands on boundaries by construction, and since s[a..b] traps on a mid-character bound, that is a guarantee rather than a convention.

import sysl.text.char_indices

var s = "héllo"

for pair in char_indices(s.bytes)
    val (i, c) = pair
    print(i, c)
0 h
1 é
3 l
4 l
5 o

The offsets go 0 1 3 rather than 0 1 2 because the é is two bytes. char_indices wraps a Chars rather than decoding for itself, so there is one decoder and the two cursors cannot disagree about a width.

is_char_boundary asks the same question about a single byte — one mask and one comparison, since a continuation byte is the only kind matching 10xxxxxx. It serves a program walking backwards, or snapping an arbitrary offset onto a boundary:

import sysl.text.is_char_boundary

var s = "héllo"
var b = s.bytes

print(is_char_boundary(b[1]), is_char_boundary(b[2]), is_char_boundary(b[3]))
true false true

Comparison is by bytes

==, < and the rest compare the byte sequences. For well-formed UTF-8 that is also code point order. A literal is also a pattern, matched by the same comparison:

var s = "héllo"

print("abc" < "abd", "abc" == "abc", s == "héllo")

var verdict = "yes" match
    "no" -> 0
    "yes" -> 1
    else 2

print(verdict)
true true true
1

Normalization is not applied. Swift’s == compares by canonical equivalence, so a composed "é" equals a decomposed one. That suits user-facing text but is surprising and expensive in systems code, where a string is usually a path, a device name, or a protocol token that must compare as the bytes it is. Normalization and collation are library operations, applied where they are wanted and visible when they cost something.

Concatenation

a + b joins two strings and s += t appends onto a slot. Both allocate: the result is a fresh buffer — an ordinary counted heap object — so it owns a count of its own and frees itself like any other reference. UTF-8 is closed under concatenation, so the result is valid without being re-checked. The operands are copied out rather than aliased, so an operand that was itself a substring keeps no hold on the result.

var a = "hé"
var t = a + "llo"

t += "!"

print(t, t.len)
héllo! 7

+ is strict: it joins a string to a string and nothing else.

var n = 7

print("n=" + n)
'+' needs matching types, got string and int

Turning a number into text is not a lossless conversion, and the language inserts only lossless ones (§ Which conversions are implicit). A string built from values of other types is written with interpolation, where the conversion is visible at the point it happens; a + that accepted “anything with a string form” would hide it.

+ is the only arithmetic operator a string defines. The rest are rejected as they are for any type that does not define them.

Rendering a value

x.to_string() is the written conversion from a value to its string form — the counterpart to the strict +, and what interpolation is built on. Every value has it: the compiler supplies the member wherever the type does not declare one of that name, so it needs no import and no impl.

val n = 42

print(n.to_string(), true.to_string(), 'é'.to_string(), 2.5.to_string(), "already".to_string())
42 true é 2.5 already

str is an ordinary name: a function, local, type or member of your own may be called str.

typeresult
integerits decimal digits, with a sign for a negative signed value
bool"true" or "false"
charthe one scalar value’s UTF-8
floatthe rendering print gives it — the fewest digits that read back at its own width, positionally, as Rust’s {} writes them
stringitself, unchanged

A name you declare wins over a built-in one of the same spelling. A type that declares its own to_string (or debug_string) member — in its body, an impl block, or a trait it implements — has that one called; the compiler’s is what a call reaches only where nothing else claims the name. So do the forms: print, str_cast, str_alias, ptr_cast and the va_ forms (the casts imported from sysl.raw and the va_ forms from sysl.c, the rest in scope everywhere) yield to a local, a parameter or a function of the same name, which is ordinary shadowing, and a call through it means that name, which is an error at the call if it cannot be called. An interpolation hole is the one call that always reaches the rendering, so a parameter called str can still be spliced in.

struct Ticket
    n: int

    to_string(self) -> string = s"#${self.n}"

print(Ticket(7).to_string(), Ticket(7))
#7 Ticket(n: 7)
double(str: string) -> string = s"${str}${str}"

str(x: int) -> int = x * 2

width(print: string) -> usize = print.len

print(double("ab"), str(21), width("four"))
abab 42 4

A call of str with no declaration of the name in scope is an unknown function:

print(str(21))
undefined function 'str'

A string is returned as it is, and a bool renders to one of two immortal literals, so neither allocates; every other case allocates a fresh buffer. A value that renders itself through its Display or Debug writes into 64 bytes of scratch in the rendering’s own frame, so a rendering of up to 64 bytes allocates only the string it ends in; a longer one moves its bytes to the heap as it grows past them, and that storage becomes the string, so a rendering that outgrows the frame once still costs one allocation. Nothing points into the frame afterwards, so the string may be returned, stored or captured like any other. Every number is rendered without the C library. An integer’s digits are divided out into a scratch buffer, which is correct even for the most negative value because the magnitude is taken in unsigned arithmetic. A float goes through the library’s sysl.fmt.format_real_plain (or its sibling at the float’s width), whose digits are the ones print writes, so x.to_string() and print(x) can never disagree and a board with no C library renders one the same way.

Every other value renders too: through Display where it has one, and through Debug where it does not. Every type has a Debug — the compiler supplies one for each struct and enum that does not write its own — so nothing is refused for having no string form. A struct shows its name and its fields, an enum the variant under the enum’s name:

struct Point
    x: int
    y: int

enum Shape
    Circle(r: int)
    Dot

var p = Point(1, 2)

print(p.to_string())
print(p, Circle(3), Dot)
Point(x: 1, y: 2)
Point(x: 1, y: 2) Shape.Circle(r: 3) Shape.Dot

Display is the override, not the requirement. Written, it is what to_string, print and a hole reach — the member takes the writer the string is being gathered into and the specifier the call site asked for:

struct Point
    x: int
    y: int

impl Display for Point
    display(self, out: *Writer, fmt: FormatSpec) =
        display_pad(s"(${self.x}, ${self.y})".bytes, out, fmt)

var p = Point(1, 2)

print(p.to_string())
(1, 2)

A reference renders as what it refers to. A member call reaches through one & to find an impl — which is why no block may be written for &T itself — and to_string, print, an interpolation hole and a format hole reach through the same one level. A &P, a &sync P and a &Buf[int] render exactly as the P or the Buf would:

struct Point
    x: int
    y: int

impl Display for Point
    display(self, out: *Writer, fmt: FormatSpec) =
        display_pad(s"(${self.x}, ${self.y})".bytes, out, fmt)

var p: &Point = Point(1, 2)

print(p)
print(s"at $p")
(1, 2)
at (1, 2)

So a reference whose referent has no Display prints the referent’s Debug:

struct Point
    x: int
    y: int

var p: &Point = Point(1, 2)

print(p)
Point(x: 1, y: 2)

A raw pointer is not reached through — what it points at may be gone — so it prints its address in lower-case hex, the null one as 0x0. A trait object keeps its reference, since the reference is what carries its table, and prints its concrete value: through Display where the trait requires it, and otherwise through the Debug every table carries. A callable prints as <fn>, and a &Writer as <writer>, their tables carrying no Debug slot; a trait such as trait LoggedWriter: Writer + Debug puts it back, so its objects print the concrete sink (what is shown by rule). Printing such a placeholder directly builds, with a warning that names the value and what to print instead.

import sysl.raw.ptr_cast

trait Area
    area(self) -> int

struct Square
    side: int

impl Area for Square
    area(self) -> int = self.side * self.side

val z: *int = ptr_cast(0)
val p: *int = ptr_cast(0x1000)
val a: *Area = &Square(3)
val f: &Fn(int) -> int = x -> x + 1

print(z, p, a, f)
0x0 0x1000 Square(side: 3) <fn>

Interpolation

An interpolated string is a literal with a prefix, and inside it $name or ${ expression } splices a value in. $$ is one literal dollar.

var n = 7

print(s"n is $n, ${n * 2} doubled, $$5")
n is 7, 14 doubled, $5

Each spliced value is rendered as to_string renders it, so the same rules apply: a primitive renders, a type with a Display renders through it, and every other value through its Debug. The whole form desugars to operations already described — s"a${e}b" is exactly "a" + e.to_string() + "b" — so an interpolation is not a new kind of value, only a concise way to write a concatenation. A hole holds a full expression, which may itself interpolate, and an empty literal segment beside a hole is dropped, since it is the identity under +.

The concatenation is the meaning; the cost is one string. A whole interpolation is built in one buffer: its text is copied in, a number or a character renders straight into it, a value with a Display or Debug writes itself into it, a nested interpolation’s pieces join it, and the string comes out once at the end. It starts in the same 64 bytes of frame scratch as any rendering, so an interpolation of up to 64 bytes allocates only its result, and a longer one the storage it grew into, which becomes the result. No intermediate string is made for each +. A hole that can leave the expression early, with ?, is the one exception: there the pieces are joined as written, so that nothing built so far is lost on the way out.

struct Point
    x: int
    y: int

impl Display for Point
    display(self, out: *Writer, fmt: FormatSpec) = out.write(f"(${self.x}, ${self.y})".bytes)

val p = Point(3, -4)
val c = 'é'
val n: i64 = -9223372036854775807 - 1

print(f"p=${p} c=$c n=$n nested=${f"[${p.x}]"} ok=${true}")
p=(3, -4) c=é n=-9223372036854775808 nested=[3] ok=true

The form is like Scala’s interpolators rather than a printf-style format string: the value and the text around it stay together where they are read, and the conversion is to_string applied at the splice rather than a directive parsed out of a separate string.

Format specifiers

f"…" adds one thing: a hole may be followed by a printf specifier controlling width, precision, sign and justification.

var n = 7

print(f"${n}%03d|${2.5}%08.2f|${"hi"}%-5s|")
007|00002.50|hi   |

A hole with no specifier renders as to_string does, exactly as in an s"…" string. A specifier binds only to the % written immediately after a hole, so a bare % elsewhere in the text — f"${n}%d done, 100% sure" — is ordinary text. Writing the specifier after the hole keeps it beside the value it formats.

The conversion is checked against the value’s type while compiling:

var n = 7

print(f"${n}%s")
format '%s' expects a string, but the value has type int

%? takes any value (below), %d %i %x %X %o %u %b want an integer, %f %e %g %E %G a float or a fixed-point value, and %s a string or any value that is not a scalar, which renders as to_string would render it. An unsigned conversion reads the value at its own width — %x of an i32 -1 is ffffffff, of a u8 255 is ff — while %d keeps the value’s sign; %b is binary, and # gives it a 0b. Under %s a width and a precision count bytes, as C’s do, and an interior NUL ends the field there, as it does for any %s.

val n: i8 = -6

print(f"[${n}%+05d] [${n}%x] [${n}%#o] [${255}%#b] [${42}%-6u]")
[-0006] [fa] [0372] [0b11111111] [42    ]

An integer of any width renders whole. Every conversion reads every bit of the value, a u256 or an i1024 as much as a u8, and %d prints what to_string does:

val wide: u256 = (1 << 255) + 0xabc
val low: i256 = -(1 << 200)

print(f"${wide}%x")
print(f"${wide}%d")
print(f"${low}%d")
print(f"[${low}%#x]")
8000000000000000000000000000000000000000000000000000000000000abc
57896044618658097711785492504343953926634992332820282019728792003956564822716
-1606938044258990275541962092341162602522202993782792835301376
[0xffffffffffffff00000000000000000000000000000000000000000000000000]
val name = "zoë"
val cut = 2

print(f"[${name}%-6s] [${name}%6s] [${name}%.${cut}s] [${name}%-8.${cut}s]")
[zoë  ] [  zoë] [zo] [zo      ]

Every conversion is rendered by sysl itself, flag for flag as C renders it — an integer by sysl.fmt.format_int (format_int_wide above 128 bits), a string by sysl.fmt.format_str, a float by format_real, whose digits are the exact value’s, rounded half to even at whatever precision is asked, and a fixed-point value by format_fixed, from its raw integer and equally exactly — so a specifier works the same on a target with no C library. An integer, a string, a float and a fixed-point specifier, a plain hole of a float and to_string of one all build for a bare board, with no snprintf for its link to find:

@export("probe")
probe(n: int, x: real, y: f32, g: q31) -> usize
    val s = if n > 0 then "up" else "down"

    f"[${n}%-6d] [${s}%8s] ${x}%.3f ${y}%e ${g}%.4f".bytes.len + s"$x".bytes.len + y.to_string().bytes.len

A width or a precision may be a hole of its own, read when the line runs — C’s %*d and %.*f, written where the digits would go. Flags stay as they are, and either count, or both, may be a hole:

val x = 3.14159265

for n in [0, 2, 6]
    print(f"[${x}%.${n}f] [${42}%0${n + 3}d]")
[3] [042]
[3.14] [00042]
[3.141593] [000000042]

The count may be any integer up to 64 bits, saturated at C’s int. A negative count is read as C reads one: a negative width left-justifies the field at its magnitude, and a negative precision is as though none was written. A negative constant is refused, the - flag being how a field is written left-justified. A value whose type renders itself is handed the counts in its FormatSpec, exactly as it is handed written digits. A count that is not an integer is refused:

val x = 1.5

print(f"${x}%.${x}f")
a width or precision written as a hole is a count, so it has to be an integer — but this one has type real

%? shows any value through its Debug, even one with a Display — the structure rather than the presentation, with a string inside it quoted and escaped. A width pads the whole rendering. x.debug_string() is the same thing as a string, with no width — a member every value has, as to_string is, and one a type’s own debug_string member overrides:

struct Point
    x: int
    y: int

impl Display for Point
    display(self, out: *Writer, fmt: FormatSpec) =
        display_pad(s"(${self.x}, ${self.y})".bytes, out, fmt)

val p = Point(1, 2)

print(f"${p} [${p}%20?] ${"hi"}%?")
print(p.debug_string(), 'c'.debug_string(), Some("x").debug_string())
print(p.to_string(), p.debug_string())
(1, 2) [   Point(x: 1, y: 2)] "hi"
Point(x: 1, y: 2) 'c' Some("x")
(1, 2) Point(x: 1, y: 2)

debug(x) is the older spelling, still accepted. It yields to a function or a local of that name, as embed does, since it is a common word for a program to use for its own purposes.

s, raw and f are only prefixes when written directly against the opening quote. Used as ordinary names they are unaffected, so s + raw and f + 1 are ordinary expressions.

Literals

Double-quoted and UTF-8, with the usual escape table. A one-quote literal may not span a line break, and a comment marker inside one is ordinary text. raw"…" does no escape decoding:

print(raw"a\nb".len, "a\nb".len, raw"a\nb")
4 3 a\nb

Where a [N]u8 is expected, a literal of exactly N UTF-8 bytes is that array instead of a string — val oem: [8]u8 = "MSWIN4.1" (arrays).

Text blocks

A literal that spans lines is written """ … """. The content begins on the line after the opening delimiter, so the opening delimiter’s own column plays no part in the indentation rule and the form reads the same at any depth of nesting.

run() -> string
    val block = """
        one
          two
        three
        """
    block

print(run().len)
prints(run())
16
one
  two
three

Three things happen to a line inside a block that do not happen inside "…".

Its incidental indentation is dropped. The strip is the least indented line that carries content, together with the line the closing delimiter sits on when it sits alone on one — so the closing delimiter is the control, and there is no margin character to remember. Move it left and the value keeps more indentation; move it right and it keeps less. This matters in an indentation-based language: a block written inside an indented body would otherwise carry that body’s indentation in its value, and the depth at which code sits should not change its data.

Its trailing blanks are dropped, because whitespace at the end of a line is invisible in a source file and would otherwise enter the value unseen. One that is meant is written \u{20}, which survives because escapes are read after the trimming rather than before it. A carriage return goes with the rest of a line’s trailing whitespace, so a block means the same thing in a file with either line ending.

A \ at the end of a line joins it to the next, for embedded data that must have no line breaks in its value at all.

digest() -> string
    """
    dead\
    beef\
    cafe
    """

prints(digest())
deadbeefcafe

The joining happens in the lexer, so a block is a single constant — where the same data assembled with + allocates and copies once per piece.

Whether the value ends with a newline needs no rule of its own: a closing delimiter alone on its line is reached after the last content line’s break has been taken, and one that follows content is reached before any break at all. A lone " inside a block is ordinary text; a block cannot end with one, and \" writes it there.

The prefixes are orthogonal to the quote form. c""", s""", f""" and raw""" all compose, since a prefix says how a literal is read and the quote form says how it was written. A raw block does no escape decoding, so nothing joins its lines.

Making new bytes

Four operations produce a string that is not a substring of one already there.

s.copy() stops a substring holding its parent alive. Slicing is O(1) and shares the buffer, so a small substring keeps the whole parent buffer alive, as in Go. Swift addresses that with a distinct Substring type that must be copied out of explicitly; sysl keeps one type and names the operation that copies out.

var big = "the quick brown fox"
var piece = big[4..<9]
var alone = piece.copy()

print(piece, alone, piece == alone)
quick quick true

string(c) encodes one scalar value:

print(string('é').len, string('a'))
2 a

str_builder() gathers text without rebuilding what it already has. Concatenation allocates a fresh buffer each time, so building a string a piece at a time with += copies everything it has so far on every step:

import sysl.text.str_builder

var sb = str_builder()

sb.push("n=")
sb.push_int(42)
sb.push_char('!')

print(sb.finish())
n=42!

Every way in carries the guarantee. A push takes a string, a push_char takes a char, and the four renderers take a number or a bool — UTF-8 is closed under appending any of them, so finish hands back a plain string rather than something a caller has to validate. For the same reason a builder is not a Writer: a public write taking a []u8 would be an unchecked conversion without the unsafe name that marks one.

push_int, push_uint, push_real and push_bool let a number be appended with no allocation — push(n.to_string()) builds a whole counted string, copies its bytes out and drops it, for text of a few dozen bytes that is needed only inside this buffer. They agree with to_string to the byte, so a line built partly with a builder and partly with an interpolation renders each number identically.

finish copies rather than lending, so a builder may go on being appended to and the string already taken out of it does not change. The alternative — handing over the storage and leaving the builder empty — would save a copy at the cost of a form whose meaning depends on how many times it has been called.

cstring(s) is the fourth, and it is the next section.

C interop

A string has no terminator, so passing one to C is an explicit, allocating conversion. CString owns the copy: Go’s version hands back a raw pointer and requires a matching free, and sysl has no manual free to match, so the result is a value whose bytes go when it does. It offers two things — cs.ptr, the *u8 a C function takes, and cs.len, the byte length not counting the terminator, so that it agrees with the s.len it came from.

import sysl.text.cstring

extern strlen(s: *u8) -> usize

var cs = cstring("a\u{0}b")

print(cs.len, strlen(cs.ptr))
3 1

That disagreement is why the conversion is written rather than inferred. For cstring("a\u{0}b"), cs.len is 3 and C’s strlen is 1. Both are correct, and neither can be made to equal the other. The pointer follows a raw pointer’s rule: it is valid while the CString is held, and keeping it past that is the ordinary raw-pointer mistake. Passing cstring(s).ptr straight into a call is safe, since the temporary lives for the statement; storing that pointer and using it later is not.

The literal case needs no allocation at all, and is spelled c"…". The compiler emits a NUL byte after every string literal in read-only data — one byte, not counted in len — so a literal is already sitting in memory in exactly the shape C reads. c"…" is that constant’s address: a plain *u8, no allocation, no copy, no runtime.

extern strlen(s: *u8) -> usize

print(strlen(c"hello"))
5

It is a distinct literal form rather than an inferred optimization: a reader should not have to work out whether an expression is a literal, and a rule that silently allocates for s but not for "…" would hide a cost the language otherwise shows. Rust’s c"…" and Zig’s null-terminated literals exist for the same reason.

A c"…" containing an interior NUL is a compile error rather than a truncation:

extern strlen(s: *u8) -> usize

print(strlen(c"a\u{0}b"))
a C string ends at its first NUL, so it cannot contain one

An ordinary "a\u{0}b" is unaffected — it carries its length, so it has three bytes and prints all three. Only the allocation-free route to C is refused, and the diagnostic is reported there.

A string handed by value to an extern is lent for the call. A long string’s three words cross as they are; a short one crosses as a long-shaped copy whose pointer is a slot of the caller’s frame, valid until the call returns. A C function that holds the string past the call says so with @keeps, and then gets a heap copy carrying a count of its own. C that reads a sysl string’s words through memory — a string field of a struct it was handed a pointer to — sees the form itself, and reads the table above: the top bit of the length word’s top byte says which.

The allocator-free subset

The type is not gated; the operations that make new bytes are. Legal under no alloc: holding, passing, comparing, indexing, slicing, iterating and releasing any string — including a heap-backed one handed in from outside, which frees itself through its own deallocation hook.

@no_alloc
@no_os

var name = "/dev/console"
var tail = name[5..]

var count = 0

for c in name.chars do count += 1

print(tail, name.len, name[0], count, tail == "console", name < "/dev/null")
console 12 47 12 true true

A module-level val may hold one, which is where a table of messages lives, and it costs nothing: a literal allocates nothing, so the table is complete before the program starts and a module with @no_alloc may carry it (declarations):

@no_alloc

val messages = ["out of range", "not permitted", "no such device"]

var i = 2

print(messages[i], messages[i].len, messages[0][0..<3])
no such device 14 out

A const would not serve here: a constant is folded into its uses and has no address, so there is nothing to index at i.

Requiring an allocator: from_utf8, copy(), concatenation, string(c), str_builder() and cstring — every operation that produces new bytes.

@no_alloc

var greeting = "hello"
var full = greeting + " world"

print(full)
the string two strings join into needs an allocator, and this module declared '@no_alloc'

With the short form on, a .bytes that would outlive the frame needs one too, unless the string is known to hold its bytes elsewhere. A string handed in may then be short, and a short string’s bytes are copied to the heap to outlive the frame that took them, so a module with no allocator may lend, index and iterate s.bytes but not return or store it; returning it is refused with “this view of ‘s.bytes’ is returned, and the string may hold its bytes in itself”. A literal’s bytes, a cut of a literal’s and str_view‘s are never copied, and pass. With the form off, the default, every string’s bytes are elsewhere, so this compiles:

@no_alloc

param_view(s: string) -> []const u8 = s.bytes

print(param_view("abcdefgh"[0..<3]).len)
3

The rule that makes the subset usable is that such a module may hold and release storage made elsewhere, and may make none of its own. So a module that only ever uses literals sees only immortal strings and its retain and release compile away entirely; one that is handed a heap-backed string pays ordinary refcount traffic and still links no allocator.

What lives in the library

Everything the compiler writes for itself is reachable without an import, and everything a program writes by name is sysl.text. A literal, +, x.to_string(), an interpolation and s.chars are all desugarings, so they cost no import — even s.chars, whose cursor is the library’s, because the compiler names it by key rather than by resolving the word.

Named at the call site, and so imported: from_utf8, char_from_u32, str_builder, cstring, char_indices, is_char_boundary, the parse_* family, the text operations split, fields, join, repeat, replace_all, replace_first, to_upper and to_lower, the Search and Ascii traits, and the types Utf8Error, ParseError, Chars, CharIndices, StrBuilder and CString. This is the division the modules page describes: what every program needs is available without an import, and everything else is imported by name.

Relationship to slices

A string is exactly an immutable, validated []u8 — the same three words, the same retain-on-slice, one implementation underneath. Everything on this page about sharing and immortality is the general slice rule rather than a string special case, and ownership crosses a no alloc boundary for the general reason: every counted object carries a pointer to the function that frees it.

The string-specific additions are two. The first is the short form: a slice’s three words always name storage elsewhere, while a string’s may be its bytes, which is why s.bytes of one is a copy in the frame and why a slice is never short.

The second is the validity invariant. A []u8 may hold any bytes and a string is the subset that is well-formed UTF-8, which is why converting between them is checked in one direction and free in the other.

GoSwiftRustsysl
size16 B16 B packed24 B / 16 B24 B
representations132 types2, one type (≤ 15 bytes in the value)
owns its bytesthe collector doesyesString yes, &str noyes
O(1) substringyesyes, Substringyes, &stryes
valid UTF-8 guaranteednoyesyesyes
elementbyte / runegrapheme clusterbyte / charbyte / char
comparisonbytescanonical equivalencebytesbytes
NUL-terminatednoprivatelynono
usable without an allocatornono&str yesyes

Bytes that are not text

Because a string is always well-formed UTF-8, a string literal cannot hold a byte that is not part of a character: its \xNN stops at \x7F, and above that the refusal names the form that can.

val input = "a\xFFb"
'\xFF' is not UTF-8 — a string holds well-formed UTF-8; write b"\xFF" for bytes

That form is the byte string, b"…": a []const u8 of exactly the bytes written, laid down as constant data and viewed in place like a string literal. It is the literal for a decoder’s malformed input, a file’s magic number or a protocol frame, and it compares with bytes made at run time as any two views do:

import sysl.buf.{Buf, buf}
import sysl.text.from_utf8

var got: Buf[u8] = buf()

got.push(0x7F)
got.push('E')
print(got.view() == b"\x7FE", from_utf8(b"a\xFFb").is_err(), from_utf8(b"caf\xC3\xA9").unwrap())
true true café

Next: traits.

Search

Esc
↑↓ to navigate ↵ to open Esc to close