Text basics and the small-object allocator (roadmap #46, speed plan step 3)
New built-ins
| function | type | rule |
|---|---|---|
parse_int(s) | (Str) -> Option[Int] | optional +/-, then one or more ASCII digits; None for anything else or out of range |
parse_float(s) | (Str) -> Option[Float] | decimal only: optional sign, digits with optional fraction (at least one digit), optional exponent; no spaces, inf, nan or hex; correctly rounded; too large gives inf |
starts_with(s, p) / ends_with(s, p) | (Str, Str) -> Bool | |
trim(s) | (Str) -> Str | removes ASCII spaces, tabs, newlines and carriage returns at both ends |
format_float(x, d) | (Float, Int) -> Str | exactly d decimals (0 to 17), correctly rounded from the exact binary value (so 1.125 → "1.12": it is a tie, and ties go to even); NaN, inf, -inf as str prints them |
Bad input is a value (None), not a crash. examples/text.tr parses a small CSV with them. All three engines agree (shared rules in src/text.rs, mirrored in the C runtime), and the differential fuzzer generates calls on edge values (including MIN, MAX and near-MAX numbers).
Slices, searching, replacing, case (M1)
| type | rule | |
|---|---|---|
x[a:b], x[:b], x[a:] | List or Str | elements or characters a to b - 1; needs 0 <= a <= b <= len(x), else an error |
find(s, sub) | (Str, Str) -> Option[Int] | the character index of the first sub; an empty sub is found at 0 |
replace(s, old, new) | (Str, Str, Str) -> Str | every old, left to right, without overlaps (replace("aaa", "aa", "b") is "ba"); an empty old is an error |
lower(s) / upper(s) | (Str) -> Str | ASCII letters only ("WÖRLD" -> "wÖrld"): the same in every engine and on every platform |
Indexes count characters, as s[i] and len(s) do. A slice is strict rather than clamped (Python's s[:100] of a short string is an error here), like indexing: a wrong bound is usually a bug, and the error says which bound and the length. The rules live in src/text.rs and runtime/trine_rt.h; natively, slicing a list copies its storage in one go (numbers and all-Float records stay flat).
for c in s loops over the characters of s (the checker rewrites it to for c in chars(s) once it knows s is a Str), and s * n repeats a string ("-" * 20; built with pushes and one join, so it is linear in the result). f-strings take a width and an alignment: {x:>8}, {x:<8}, {x:^8}, with decimals {x:>8.2}; numbers align right by default, other values left, and a width never truncates.
f-strings and characters (#49)
f"{name}: {qty} x {price:.2}" is name + ": " + str(qty) + ... with format_float(price, 2) for :.2. Any expression goes inside the braces (strings and nested f-strings included); {{ and }} are literal braces. The rewrite happens in the parser, so every engine and tool sees ordinary + and str calls. Plain "..." strings are unchanged: braces in them are just braces (JSON-heavy code keeps working), which is why interpolation needs the f.
Characters stay one-character strings, as in Python: ord("A") is 65, chr(955) is "λ" (non-characters such as surrogates are a runtime error). A separate Char type was considered and dropped: chars(s) returning List[Str] is what existing code relies on, and the speed a Char type would bring is already there (one-character ASCII strings are interned, no allocation). Digit arithmetic is ord(c) - ord("0"). examples/fstrings.tr shows both.
Earlier note, kept for history: a Char type. Its main payoff was speed, and chars(s) and s[i] already return interned one-character strings (no allocation). A Char type is a language design question (literals, conversions, what chars returns) better settled with modules and the formatter than inside a speed step.
Speed: where the time went, and what changed
Profile of bench/v1/strings (callgrind, instructions): 2.11 G before.
| change | why |
|---|---|
| Small-object pool | malloc/free were ~31% of the work. Objects of up to 256 bytes (most strings, constructors, closures, list headers) and small list buffers now come from per-size free lists: freeing pushes the cell, allocating pops one. The pool class is kept in the object header's spare 4 bytes (and the list header's for its buffer), so no size lookup. A unique pooled string grows in place while it fits its cell, and moves to malloc when it outgrows it. |
**split with memchr** | split compared the separator at every byte with memcmp (7%). It now jumps to the separator's first byte with memchr. |
| Known-ASCII strings | pieces of an ASCII string, and str(Int), skip the UTF-8 character count; the count itself runs eight bytes at a time on ASCII. |
| Inline push | appending with room left and matching storage is inline; growth stays out of line. |
| Short string patterns | match c: "0" => ... compares bytes inline instead of calling memcmp. |
strings: 2.11 G → 1.04 G instructions. trees (allocation-bound) benefits most: it is now faster than the C version, which pays for malloc/free.
Safety of the pool. Under AddressSanitizer the pool is off, so sanitized fuzzing still detects use-after-free. Debug builds (TRINE_VERIFY_BOUNDS, used by the native fuzzer) fill freed cells with 0xAB, so a use after free reads garbage and shows up as a disagreement with the interpreter rather than reading stale but plausible data. TRINE_LEAKCHECK still counts live objects. The pool never returns memory to the OS: a program's footprint is its peak.
Also in this step: an element read that is a list's last use (let x = xs[i] with xs dropped right after) moves the element out of a unique list instead of sharing it.
Found, not fixed: unpacking dying containers (#48)
examples/text.tr removes 77% of reference-counting overhead, below bet 1's 90% bar. The cause is a pattern common in parsing: match parse_row(line): Some(r) => ..., where the Option dies immediately. Today r is dup'ed and the Option dropped: two rc operations that a unique Option doesn't need. The test carries a documented exception for this file until #48 lands.