ADR 0143: Binary Construction Syntax

Status

Implemented (2026-11-03); accepted 2026-11-01. Epic BT-4138. Amended 2026-11-03 (BT-4380) to match the match-side semantics that shipped in BT-4143 (#4729) and BT-4376 (#4759), and to settle the design questions the first draft left open (§ Segment values, § Literal checks, § String values, § Result class, § Runtime failures).

Implemented note (2026-11-03). Shipped as described, except: the run-time error reads OTP's wording, "binary construction: segment 2 of type 'binary': expected a binary but got: 1", naming the 1-based source segment (codegen emits the Core {segment, N} annotation, BT-4414), its type and the value (§ Runtime failures; BT-4406). The String unwrap is skipped only for a nested construction, not for values typed Binary (§ String values; BT-4407). A parenthesised string literal (<<("hi")/binary>>) is still a string literal, so it gets the same compile error as <<"hi"/binary>>.

Context

BT-4096/4097/4098 completed binary pattern matching: <<n:8, payload:n/binary>> parses in match arms and lowers to Core Erlang binary matching. Erlang's other half — building binaries — has no Beamtalk equivalent. Encoding stays manual:

frame := Binary fromBytes: #(16, 3) concat: payload

Buccaneer needs construction for HTTP/2 frame encoding, where a frame is a mix of integer fields, flags, and payload bytes. The manual route works but hides the wire layout and cannot express sub-byte fields or sizes computed from values in one place.

Current state

Constraints

Decision

Reuse <<...>> in expression position with the same segment grammar as patterns. One grammar, two directions: in a match arm <<...>> destructures, in an expression it builds.

len := payload size
frame := <<16:8, 3:8, len:24, payload/binary>>
frame match: [<<16:8, 3:8, n:24, rest:n/binary>> -> rest toBytes]

Segment shape (mirrors BinarySegment, values are expressions):

<<v:4>>                        // integer value, 4 bits
<<p/binary>>                   // whole binary
<<s:8/unit:2>>                 // size 8, unit 2 (16 bits)
<<1.5/float>>                  // float literal
<<$A>>                         // character literal (65)
<<"hi">>                       // string literal (raw bytes, no /binary needed)
<<h:16/big-unsigned-integer>>   // spelled type chain, same vocabulary as patterns

REPL sketch (after implementation):

> payload := Binary fromBytes: #(104, 105)
> <<16:8, payload/binary>> size
3
> <<16:8, payload/binary>> toBytes
#(16, 104, 105)

Diagnostic examples:

> <<v:4>>                      // v unbound
ERROR: unresolved identifier 'v'
> <<(-1):4>>                   // literal out of range: warns, as in patterns
WARNING: the value -1 does not fit in an 'unsigned' binary segment of size 4 and is truncated to 15
> <<"hi"/binary>>              // can never succeed: error, as in patterns
ERROR: a literal string in a binary pattern must not have a type or a size

Core lowering is the same #{...}# construction the match side and string interpolation already emit. Verified against erlc +to_core (2026-11-01):

%% t1(V, P) -> <<V:4, P/binary>>.
#{#<V>(4,1,'integer',['unsigned'|['big']]),
  #<P>(('all'|'compiler_generated'),8,'binary',['unsigned'|['big']])}#
%% <<N:8/unit:2>>  ->  (8,2,'integer',['unsigned'|['big']])
%% <<1.5/float>>   ->  8 constant integer segments (constant-folded bytes)
%% <<$A>>          ->  #{#<65>(8,1,'integer',['unsigned'|['big']])}#
%% <<"hi"/utf16-big>> -> #{#<0>...,#<104>...,#<0>...,#<105>...}#

Note: erlc does not reject <<"hi"/binary>> as a construction. It warns ("binary construction will fail because of a type mismatch") and the expression raises badarg at run time; in a pattern the same segment is a compile error ("a literal string in a binary pattern must not have a type or a size"). Beamtalk makes it a compile error in both directions (§ Literal checks). The construction spelling for embedded bytes is the bare string literal <<"hi">>; the /binary suffix is for variables, as on the match side.

Segment values

name:size lexes as one keyword token (Keyword("name:")), so a segment value cannot be an arbitrary expression: <<x size:8>> would read as the keyword send x size: 8. A construction segment value is therefore restricted to what the match side already accepts in that position, plus parentheses:

Sizes keep the pattern rule: an integer literal, a variable, or a parenthesised expression. Anything else is a parse error whose hint is to parenthesise. One segment parser serves both directions; the value production differs only in admitting a parenthesised expression where a pattern admits _.

Literal checks

One policy for both directions: a literal that cannot do what its segment asks is a warning, unless the segment can never succeed at all, in which case it is an error. Concretely:

ShapePattern (shipped, #4729/#4759)Construction (this ADR)erlc construction
Integer literal does not fit (<<300>>, <<(-1):4>>)warning: arm never matcheswarning; the value is truncated to its low bitssilent truncation (<<15:4>>)
Float literal in a non-float segment (<<1.5>>)warningwarning; raises at run timewarning, run-time badarg
Integer literal in a binary/bits segmentwarningwarning; raises at run timewarning, run-time badarg
Float size not 16/32/64 bitswarningwarningwarning
Non-ASCII character in a default 8-bit segment (<<$é>>)warningwarning; builds byte 233silent
Type/size on a string literal (<<"hi"/binary>>)errorerrorwarning, run-time badarg
Negative literal size; size/unit on utf*; unit: without a size on integer/float; conflicting unit:errorerrorerror

Why warnings for misfits rather than errors (the first draft said errors):

The error rows are the shapes that can never produce a value. <<"hi"/binary>> always raises; reporting that at compile time costs nothing and is what the match side already does through the shared check_binary_literal_shapes.

String values

A String is the tagged term {beamtalk_string, Bytes} (BT-4173), so a String held in a variable is not a BEAM binary. Construction treats it the way the match side treats a String subject, by its UTF-8 bytes:

Result class

Construction always builds bytes, never text: the result is never a String (class is construction type, BT-4170; use asString or String fromIolist: to get one). Per ADR 0141 the class follows the shape:

Statically, the type checker answers Binary when every segment's bit size is known and the sum is a multiple of 8 (literal sizes times units, default sizes, and binary/bytes/utf* segments, which are whole bytes, as is a float segment of any size: it builds 16, 32 or 64 bits or fails), and Bitstring when the known sum is not. When a bits/bitstring value or a variable size with a sub-byte unit leaves alignment unknown, it answers Bitstring | Binary, the union Bitstring>>concat: already answers; callers narrow with a :: Binary match arm.

Runtime failures

A construction that fails at run time (a non-integer in an integer segment, a variable size that is negative or not an integer, a non-binary in a binary segment, a binary segment whose size exceeds the value) raises the BEAM's badarg, with an error_info cause naming the segment ({SegmentIndex, Type, Reason, Value}, OTP's format_bs_fail).

Generated code does not wrap construction in try: success stays one allocation with no handler frame. The raw badarg reaches the existing conversion point, beamtalk_exception_handler:wrap_raw/2, which on:do:, ensure:, actor boundaries and the REPL already use, and which classifies badarg as an argument_error #beamtalk_error{}. Phase 2 extends that path to read the format_bs_fail cause, so the message names the segment and value ("binary construction: segment 2 expects a binary, got 1") instead of the generic "invalid argument".

Prior Art

User Impact

Steelman Analysis

Tension: Smalltalk purity vs one shared Erlang-shaped literal. Precedent (ADR 0023 compiling interpolation to binary construction) already resolved this trade-off toward the literal.

Alternatives Considered

Binary build: #() message form

frame := Binary build: #(#(16 size: 8), #(payload spec: #binary)))

No grammar change, fully greppable. Rejected: the wire layout disappears into nested arrays, and the specifier DSL (size:, spec:) duplicates the pattern vocabulary with different punctuation — two dialects for one thing.

Interpolation-only extension

Stretch "..." interpolation to cover bytes. Rejected: interpolation is text via printString; integer bit fields, units, and endianness do not belong in string semantics.

Separate construction-only delimiters

E.g. #b[...] or <<|...|>>. Rejected: a third spelling for the same segments, with no disambiguation benefit once the leading-<< rule exists.

Consequences

Positive

Negative

Neutral

Implementation

  1. AST: Expression::BinaryConstruction { segments, span } reusing BinarySegmentType/BinarySignedness/BinaryEndianness; values and sizes are Expressions restricted as in § Segment values. Parser and type checker run in the caller for any blocks (class-process rule, ADR 0142): segments contain value expressions, not blocks into class methods.
  2. Parser: leading-<< in operand position parses construction; infix << is a targeted parse error (<< was never a binary selector). Same specifier parser and the same check_binary_literal_shapes as patterns (§ Literal checks), with the "can never match" wording reworded for construction ("will be truncated", "will fail").
  3. Codegen: emit #{...}# per the verified shapes; literal floats fold as erlc does; bare string literals emit their UTF-8 bytes; String values in byte segments are unwrapped (§ String values). Type checker: result class per § Result class. Runtime: a format_bs_fail clause in wrap_raw/2 (§ Runtime failures).
  4. Unparse: round-trip both directions with identical spelling.
  5. Tests: build-then-match round-trips incl. sizes from values; unparse corpus; guide section next to patterns.
  6. BT-4143 (#4729) and BT-4376 (#4759) have merged, so the shared files (parser/expressions.rs, unparse/mod.rs, guide, binary_patterns_test.bt) are free.

Implementation Tracking

Epic: BT-4138 Issues: BT-4346 (Phase 1: AST + parser + unparse) → BT-4347 (Phase 2: codegen, blocked by BT-4346) → BT-4348 (Phase 3: tests + e2e + docs, blocked by BT-4347) Status: Implemented — BT-4346 (#4782), BT-4347 (#4787), BT-4348; follow-ups BT-4406, BT-4407, BT-4414 Note: BT-4142 (design + build monolith) retired as superseded by this split; BT-4143 (match-side parity) landed in #4729 and BT-4376 (erlc unit/float alignment) in #4759; BT-4380 amended this ADR to match them.

Adoption note (2026-11-27, BT-5227)

Evidence from the downstream adoption epic (BT-5221; full report in docs/research/feature-adoption-2026.md). Binary construction and patterns now have real users in four packages.

References