ADR 0141: Bitstring — a Sealed Class for Unaligned Bitstrings

Status

Implemented (2026-10-28)

Context

BT-4097 added bits/bitstring segments to binary patterns, so a pattern can bind a tail that is not a whole number of bytes:

(Binary fromBytes: #(234)) match: [<<_:3, rest/bitstring>> -> rest]

rest here is 5 bits. It matches again fine, but nothing else works. An unaligned bitstring fails is_binary/1, so beamtalk_primitive:class_of/1 fell through to 'Object', and module_for_value/1 had no arm for it. Every Binary/Collection selector, including the two most natural ones (rest size, rest toBytes), raised Object does not understand, and the value printed as a generic Object. No semantics were defined: is size bits or bytes? Does toBytes pad, truncate, or raise?

This is a type-level question, not a lowering fix: the value needs a class.

Decision

The class follows the value's shape

A new sealed leaf class, Bitstring, is a sibling of Binary:

sealed typed Value subclass: Bitstring native: beamtalk_bitstring

The class is decided by the value's shape, as Erlang decides it. A bitstring whose bit size is a multiple of 8 is a binary, and has class Binary (or String when tagged). Any other bitstring is a Bitstring. No tag is needed:

So an operation can turn one into the other. Joining 1 bit and 7 bits answers a Binary, just as <<A/bitstring, B/bitstring>> does in Erlang.

Protocol

SelectorAnswer
bitSizeInteger, the number of bits (bit_size/1)
toBitsList(Integer) of 0/1, most significant bit first
concat: aBitstringOrBinarythe joined bits: a Binary when the total is byte-aligned, else a Bitstring. A String argument is joined by its bytes, as in Binary>>concat:
asBinaryResult(Binary, Error). Always an error for a Bitstring: kind #unaligned_bitstring, hint naming bitSize and toBits. No silent padding or truncation
printString / displayStringErlang notation, e.g. <<2:3>> (what io_lib:format("~w") prints)
=:=, ==, hashinherited structural equality

Binary gains bitSize (8 × its byte count; a String counts its UTF-8 bytes), so bitSize works on either class. Binary>>concat: stays bytes-only (Binary -> Binary): a Bitstring argument is a type_error. Widening it to Binary | Bitstring -> Binary | Bitstring would make every byte-level send on its result (toBytes, size, …) a static warning, for the rare bit case. So concatenation is asymmetric: bits are joined from the Bitstring side, whose concat: accepts a Binary or String and crosses back to Binary when the total is byte-aligned.

Everything else on Binary/Collection stays bytes-only and is deliberately not understood by Bitstring: size, do:, at:, byteAt:, part:size:, toBytes, includesSubstring:, indexOf:, asString, asStringUnchecked, asBase64, asBase64Url, asHex, and all Collection protocol (collect:, select:, inject:into:, isEmpty, includes:, …).

tail := (Binary fromBytes: #(234)) match: [<<_:3, rest/bitstring>> -> rest]
tail class        // => Bitstring
tail bitSize      // => 5
tail toBits       // => #(0, 1, 0, 1, 0)
tail printString  // => "<<10:5>>"
tail asBinary     // => Result error: (unaligned_bitstring)
tail size
// => does_not_understand: Bitstring does not understand 'size'
//    Hint: a Bitstring is not byte-aligned (5 bits); use 'bitSize'/'toBits',
//    or 'asBinary' to check alignment

Where the does-not-understand error is raised

The error is the structured does_not_understand (#beamtalk_error{}, class Bitstring, the selector), with the hint above. It comes from beamtalk_primitive:send/3's bitstring arm: the send dispatches through the compiled class as usual, and when the hierarchy walk ends in the does_not_understand for that selector on a Bitstring, the arm re-raises it with the bit-size hint. The reflection arms (fieldNames, fieldAt:, hasField:) are still reached: a Bitstring has no fields, so fieldNames answers #(), hasField: answers false and fieldAt: raises immutable_value, as for a primitive class.

It is deliberately not a Bitstring>>doesNotUnderstand:args: override in bitstring.bt. A class that overrides doesNotUnderstand:args: is "open" to the compiler: the type checker stops reporting unknown selectors on it, protocol conformance treats it as conforming to every protocol (ADR 0025 tier 3), and SystemNavigation dnuHandlers lists it. That is the opposite of "deliberately not understood": tail size on a Bitstring-typed receiver should be a compile-time warning, and tail respondsTo: #size must answer false. Raising from the send path keeps the class closed and gives the same runtime error.

Patterns

b :: Bitstring is a legal type pattern (sealed leaf). Its test is the guard-safe is_bitstring(X) andalso not is_binary(X). :: Binary is unchanged (BT-4228): a Bitstring is not a Binary. A /bitstring segment binds whatever the bits are, so its binding is Binary or Bitstring at run time; the type checker does not type segment bindings, so nothing changes statically.

Prior Art

User Impact

Steelman Analysis

Alternatives Considered

Bitstring as the superclass of Binary

Erlang's subset relation as inheritance. Rejected: Binary's Collection protocol counts bytes, so Binary would override size with a different unit than its superclass, breaking substitutability. It would also widen :: Binary / isKindOf: reasoning beyond BT-4228's closed {Binary, String} subtree.

Unaligned values as Binary, with a per-method unaligned branch

size, at: and do: have no honest byte answer for 3 bits. Every padding or truncation rule silently invents or loses data.

Forbid unaligned tails at run time

Removes BT-4097's bit-level protocol parsing (<<flags:3, v:5, rest/bitstring>>). Rejected.

A Bitstring>>doesNotUnderstand:args: override

Gives the same runtime error, but makes the class open to the type checker and protocol conformance (see Decision). Rejected in favour of raising from the send path.

Consequences

Positive

Negative

Neutral

Implementation

References