Skip to content

ADR 0025: The Str representation

Status: Final Type: Architecture Created: 2026-07-29 Amends: 0004 (the NUL-terminated const char * it first sketched gains a header) Related-ADRs: 0026 (the ownership discipline over this representation), 0024 (the memory model), 0015 (the sibling type that has a length). Provenance: arbitrations A3, A46, A64–A69.

Context

Reclaiming strings needs a reference count. O(1) len and interior NUL need lengths. A literal must stay a static blob in the data section, because a representation that allocates per literal evaluation loses before it starts. The prior representation (a bare NUL-terminated const char *) offered none of that, and all services touch Str.

Decision

A Str stays a const char * pointing at the first payload byte; the header lives at a negative offset. The payload keeps its NUL terminator, which C consumers expect.

typedef struct __pp_str_head {
    int64_t rc;       /* __PP_STR_IMMORTAL (-1) for a static literal */
    int64_t nbytes;   /* payload length, terminator excluded */
    int64_t ncp;      /* length in code points — what CPython's len() counts */
} __pp_str_head;

The instance header uses the same shape, so the uniformity is a rule: all heap values in POST point at the payload and keep the header at a negative offset. The struct is defined once and shared by the units that name it, with a compile-time sizeof == 24 assertion. The literal emitters reach the payload by adding a constant, and are correct only if that is the size.

Why a prefix and not a descriptor. The literal path decides it. A prefix literal is one static object (header words, bytes, NUL) and the emitted value is that object's address plus a constant: no backend needs a data-section relocation, which none of the three emitters had ever produced. And the C-type vocabulary stays closed: Str is still const char *, so the stable C ABI's promise ("Str exports where bytes does not, because a NUL-terminated const char * is a type C already has") stays intact, as do the pygo ABI's channel element and any 8-byte slot a Str occupies. The cost is that a prefix cannot borrow: each const char * entering POST from outside must be adopted (copied into a headered allocation).

Immortal literals. rc == -1 is the static-literal sentinel (CPython's own answer at a different width), checked in the count helpers, because "is this pointer in the data section" is not a question C can portably ask. It must be uniform across backends: a literal emitted by one and freed by another is heap corruption with no diagnostic anywhere.

One allocator. Every Str-producing site, in any runtime unit, allocates through __pp_str_alloc(nbytes, ncp). The Str runtime is a separate translation unit per backend (it owns per-task counters, and other units produce Strs, so a static copy would be callable from none of them). A representation change is thereafter a change to one function. The uses-predicate for linking the unit asks not only "does anything call a Str helper" but "is any value in the program a Str", the direction that fails closed: a missing runtime unit is a loud link failure.

The counts are exact at the producers by construction. The allocator takes final counts only. Concatenation adds two header fields, repetition multiplies one, the formatting helpers produce ASCII where ncp == nbytes, and CPython conversions bring CPython's own lengths. So the runtime contains exactly one length scan, in __pp_str_adopt, the crossing where no counts exist anywhere until something computes them. A "seal the counts afterwards" helper was rejected: it would be a second call that producers could forget. A forgotten call leaves len() wrong on all three backends at once, a failure shape byte-identical parity cannot see.

The adoption list is enumerated, on two axes. Static C literals returned into Str slots become static headered immortals. Strings arriving from CPython copy through the allocator. The stable C ABI's export wrapper adopts on entry (the one place the cost is visible to a header's user). A bytes literal's blob rides the same emitters, with the same header. The list needed a second axis the first draft missed: provenance rows must adopt too. These are pointers borrowed out of foreign objects (a CPython type name, a raise site's C literal, one stack buffer). A derived guard over the runtime's own units holds the completeness of the whole list.

Consequences

  • Interior NUL is representable: the "\x00" literal, chr(0), converted text and exception messages containing U+0000 all work. The refusals they used to meet are removed. The remaining refusals are facts about the encoding (a surrogate is not UTF-8), which no header changes.
  • len is a header read, O(1) to read and to maintain.
  • The defect class this representation creates is a NUL-terminated read behind a value that has a length. The digit parsers stopped at an interior NUL and read it as end-of-string (int("1\0002") returned 1 where CPython raises) once NUL became legal data. Readers of a Str must ask the header; the parsers and ord do now.
  • Comparison is memcmp over the common prefix then by length (what strcmp cannot be once NUL is legal data); bytewise comparison being code-point order for UTF-8 is still why no decoding is needed.
  • The C-ABI promise held, as checked through a real C caller: the emitted headers are byte-identical, the closed conversion vocabulary did not grow, and a ctypes caller still receives a readable NUL-terminated string.

Alternatives considered

  • A descriptor ({ptr, len} by value, as bytes uses): could borrow foreign buffers, but grows the closed C-ABI vocabulary, retracts the Str-exports promise, changes the pygo channel element in a header versioned elsewhere, and needs struct-constant emission in three data-section emitters. Rejected on the literal path and the ABI. bytes first took a descriptor, since it never had the export promise, and moved onto this header when it became counted (0015, A174); it still does not export.
  • Interning/pooling computed strings: out of scope; the allocator centralisation keeps it possible later without touching backends.
  • A separate type with a length beside the bare one: rejected, because no helper could tell which kind it was handed; landing the header half-way is unsound, which is why representation and migration were one decision.