Beamtalk Language Features

Language features for Beamtalk. See Design Principles for design philosophy and Syntax Rationale for syntax design decisions.

Status: v0.6.0 — implemented features are stable, including generics, protocols, union types, control flow narrowing, the typed class modifier, FFI type inference, package management with qualified pkg@Class names, native Erlang sources in packages, named actor registration, and Result-shaped supervisor lifecycles. See ADR 0068 for the type system design.

Syntax note: Beamtalk uses a modernised Smalltalk syntax: // comments (not "..."), standard math precedence (not left-to-right), and optional statement terminators (newlines work).


Table of Contents


String Encoding and UTF-8

Beamtalk strings are UTF-8 by default. This follows modern BEAM conventions and matches Elixir's approach. String is a subclass of Binary (Collection > Binary > String) — see Binary — Byte-Level Data for byte-level operations inherited by String.

String Types

// Double-quoted strings - UTF-8 binaries
name := "Alice"
greeting := "Hello, 世界! 🌍"

// String interpolation (ADR 0023)
message := "Welcome, {name}!"
emoji := "Status: {status} ✓"

// Escape sequences inside strings (ADR 0138):
//   \r   carriage return (U+000D)
//   \n   line feed (U+000A)
//   \t   horizontal tab (U+0009)
//   \\   backslash
//   \"   double quote ("" doubling still works too)
//   \0   NUL (U+0000) — exactly one char, no C-style octal continuation
//   ""   doubled delimiter → literal double-quote character
//   \{   literal { — backslash consumed (prevents interpolation)
//   \}   literal } — backslash consumed
// A backslash before anything else is a compile error pointing at the
// backslash: "\q" → unknown escape '\q' … (use '\\' for a literal backslash).
// Symbol literals (#'…') have no backslash handling: #'a\nb' is backslash-n.
// Character literals share the same escape table (BT-5182): $\n, $\t, $\r,
// $\\, $\", $\0 (NUL, as "\0" is), $\{ and $\}. Any other $\x is the same
// unknown-escape compile error; write the character itself instead ($q, $').
quote := """"                    // 1-char string containing "
dialog := "She said ""hello"""  // → She said "hello"
crlf := "\r\n"                   // 1 grapheme — byte-identical to (Character value: 13) asString ++ (Character value: 10) asString

// In Erlang, strings are tagged tuples holding UTF-8 binaries:
//   "hello"  →  {beamtalk_string, <<"hello">>}

Source text and literal limits (BT-5182). A source file may start with a UTF-8 byte-order mark, which is ignored, and may use CRLF line endings; the \r is never part of a comment's text. A string literal may span lines, but not a line that starts a class or protocol definition (Object subclass: Foo, Protocol define: P, at column 1). A string with no closing " is reported as unterminated string literal starting at line L, column C (or, when a definition line comes first, string literal starting at line L, column C is not closed before the definition on line M), covering only the line it opens on; parsing resumes on the next line, so the definitions after a missing quote still compile and still show in the editor. Block comments (/* */) do not exist: a /* is reported as block comments are not supported; use // on each line, covering the /* to the end of its line, and parsing resumes on the next line (BT-5229). Integer literals have no size limit: 100000000000000000000 and 16rFFFFFFFFFFFFFFFFFF are BEAM bignums, up to 10,000 digits, and a - written directly before a radix literal is part of it (-16rFF is -255).

Character Encoding

BeamtalkErlang/BEAMNotes
"hello"{beamtalk_string, <<"hello">>}Tagged UTF-8 binary (BT-4173)
"Hi, {name}"{beamtalk_string, <<"Hi, ", Name/binary>>}Interpolated UTF-8 (ADR 0023)
Grapheme clusterVia :string module"👨‍👩‍👧‍👦" is one grapheme, multiple codepoints
$a97 (codepoint)Character literal = Unicode codepoint

Character Methods

Character-typed receivers dispatch through the Character method table, so methods like asString, printString, uppercase, lowercase, and class return Character-appropriate values. This applies to character literals ($A), the Character value: class factory, chained uppercase/lowercase sends, ifTrue:ifFalse: conditionals whose outcome is statically Character, and single-block ifTrue:/ifFalse:/and:/or: sends whose literal receiver takes a Character-answering block — all statically Character-typed forms. A two-branch conditional is transparent when a literal condition takes the known branch, or when both branches agree (a non-constant condition with mixed branches stays Integer-dispatched). A single-block send is transparent only when its receiver is the literal that runs the block (true ifTrue:, false ifFalse:, true and:, false or:): on the other path it answers a Boolean (false ifTrue: [$A] answers false, not nil), so a non-constant receiver stays Integer-dispatched:

$A asInteger              // => 65
$A asString               // => "A"
$A printString            // => "$A"
$A uppercase              // => 65
$A lowercase              // => 97
$A class                  // => Character
$A respondsTo: #uppercase // => true
Character value: 65       // => $A
(Character value: 10) asString   // => "\n" (LF, not "10")
$a uppercase asString            // => "A"
(true ifTrue: [Character value: (48 + 6)] ifFalse: [0]) asString  // => "6"
(true and: [$A]) printString     // => "$A"
(false ifTrue: [$A]) class       // => False

String Operations (Grapheme-Aware)

String operations respect Unicode grapheme clusters (user-perceived characters):

// Length in graphemes, not bytes
"Hello" length        // => 5
"世界" length          // => 2 (not 6 bytes)
"👨‍👩‍👧‍👦" length        // => 1 (family emoji is 1 grapheme, 7 codepoints)

// Slicing by grapheme
"Hello" at: 1         // => "H"
"世界" at: 1           // => "世"

// First / last grapheme
"Hello" first         // => "H"
"Hello" last          // => "o"
"über" first          // => "ü" (one grapheme, two UTF-8 bytes)

// Iteration over graphemes
"Hello" each: [:char | Transcript show: char]

// Case conversion (locale-aware)
"HELLO" lowercase     // => "hello"
"Content-TYPE" asciiLowercase  // => "content-type" (only A-Z fold; non-ASCII untouched)
"straße" uppercase    // => "STRASSE" (German ß → SS)

Regular expressions are code-point-based on Strings (BT-5030). A String pattern (matchesRegex:, allMatches:, replaceAllRegex:with:, Regex from:, ...) compiles in Unicode mode, so indexes and lengths inside a match count code points, not bytes (. matches one code point, not one grapheme: use \X for a whole grapheme such as e plus a combining accent):

"héllo" allMatches: "."                    // => #("h", "é", "l", "l", "o")
"héllo wörld" allMatches: "\\w+"            // => #("héllo", "wörld")
"ÉCOLE" matchesRegex: "école" options: #(#caseless)  // => true

Before BT-5030 the same calls ran in byte mode: . matched one byte, so the first two raised parse_error ("Match boundary splits a multi-byte character") or, for \w, split words at every non-ASCII letter, and caseless matching ignored non-ASCII case. \d now also matches non-ASCII decimal digits; write [0-9] when only ASCII digits are wanted. A bare Erlang binary pattern passed through the FFI keeps byte semantics. startsWith:, endsWith: and includesSubstring: compare bytes, and words splits on ASCII whitespace only, while indexOf:, take: and drop: count graphemes (see the class docs).

Inherited Byte-Level Methods

String inherits byte-level methods from Binary. These provide unambiguous byte access regardless of grapheme semantics:

// Byte access (inherited from Binary)
"hello" byteAt: 0      // => 104 (byte value, 0-based)
"hello" toBytes size   // => 5 (byte count — `size` itself counts graphemes)
"café" toBytes size    // => 5 (bytes — more than 4 graphemes due to UTF-8)

// Byte-level slicing returns Binary, not String
"hello" part: 0 size: 3  // => Binary (raw bytes, not String)

// Byte-level concatenation returns Binary
"hello" concat: " world"  // => Binary (use ++ for String concatenation)

// Byte list conversion
"hello" toBytes        // => #(104, 101, 108, 108, 111)

See Binary — Byte-Level Data for the full Binary API.

BEAM Mapping

BeamtalkErlangNotes
"string"{beamtalk_string, <<"string">>}Tagged binary, not charlist
"世界"{beamtalk_string, <<228,184,150,231,149,140>>}UTF-8 encoded bytes
String operations:string moduleGrapheme-aware (:string.length/1)
$xInteger codepoint$a = 97, $世 = 19990
Charlist (legacy)[104,101,108,108,111]Via Erlang interop

Why UTF-8 by Default?

  1. Modern web/API standard - JSON, HTTP, REST APIs all use UTF-8
  2. Compact for ASCII - 1 byte per ASCII character (most code/English text)
  3. Elixir compatibility - Seamless interop with Elixir libraries
  4. BEAM convention - Erlang's :string module is Unicode-aware
  5. Agent/LLM-friendly - AI models output UTF-8; easy integration

Legacy Charlist Support

Charlists are Erlang lists of integer codepoints. Beamtalk uses binaries for strings, but you can convert when needed for Erlang interop via binary_to_list / list_to_binary.


Core Syntax

Actor Definition

Actor subclass: Counter
  state: value = 0

  increment => self.value := self.value + 1
  decrement => self.value := self.value - 1
  getValue => self.value
  incrementBy: delta => self.value := self.value + delta

Actor Lifecycle Hooks

Actors support two optional lifecycle hooks:

Actor subclass: ResourceActor
  state: handle = nil

  initialize =>
    self.handle := Resource open

  terminate: reason =>
    self.handle isNil ifFalse: [self.handle close]

  doWork => self.handle process

Key behaviour:

Aspectinitializeterminate:
Called onspawn / spawnWith:stop, stopWith:, supervisor shutdown (rest_for_one/one_for_all cascade, direct terminate:), linked exit
Error effectSpawn fails with InstantiationErrorShutdown proceeds anyway
Called on kill?N/ANo — kill bypasses terminate:
Side effect—Overriding terminate: causes the actor to trap exits (process_flag(trap_exit, true)); actors without an override keep untrapped link semantics
Actor stateAccessible via self.fieldAccessible via self.field

Both hooks are optional — actors without them work normally.

Stopping with a reason — stop stops an actor with reason #normal. stopWith: reason (and stopWith: reason timeout: ms) stops it with any reason you choose; terminate: receives exactly that reason, and so does every onExit: block. This lets an actor route its cleanup on why it stopped, OTP-style:

Server subclass: Connection
  handleInfo: msg =>
    msg == #tcp_closed ifTrue: [self stopWith: {#shutdown, #peer_closed}]

  terminate: reason =>
    reason =:= #normal ifTrue: [^nil]
    // e.g. {shutdown, peer_closed}, {shutdown, read_timeout}, or an error
    self logClose: reason

Spawn with a monitor (BT-4104). Worker spawnMonitored and Worker spawnMonitoredWith: initArgs answer a {actor, ref} Tuple (at: 1 / at: 2) whose monitor is created atomically with the process. A separate X spawn followed by monitor reports {#DOWN, ref, #process, pid, #noproc} for an actor that exits straight after initialize (for example a continueWith: step ending in stopWith: #normal); spawnMonitored delivers the real reason (#normal here). Failures raise instantiation_error like spawn, leaving no stray monitor. The actor is not linked, and supervisor classes do not support these selectors (OTP has no atomic supervisor start plus monitor).

The monitor belongs to the process that runs the spawn. Use a static send (Worker spawnMonitored) from an actor or Server method so the #DOWN reaches that process's handleInfo:. A dynamic send (cls spawnMonitored, perform:) or a send inside a class method runs in the class's process, which then owns the monitor, so its #DOWN is never seen by the sender. This is documented rather than raised, because it cannot be detected on the static-from-class-method path. Linked and named-and-monitored variants are follow-ups.

Spawn with a monitor, without waiting (BT-4477). Worker spawnMonitoredAsync and Worker spawnMonitoredAsyncWith: initArgs answer the same {actor, ref} Tuple as spawnMonitored, but at once: the caller does not wait for the new actor's init/1 or initialize. A process that starts a short-lived worker per request (an HTTP/2 connection with one process per stream) pays no start-up wait in its own loop. The monitor is still created atomically with the process, so a worker that ends immediately delivers its real reason, never #noproc.

Initialization chaining — initialize methods defined on ancestors run automatically, parent-first, before the child's own initialize. State threads through each call so the child sees the parent's mutations. Do not write super initialize yourself — the compiler warns on redundant super initialize sends inside an Actor's initialize. After the full chain runs, any typed state: field without a default (on the child or any ancestor, including cross-file parents) must have been assigned, or the actor crashes with UninitializedStateError naming the owning class. See ADR 0078.

Secret State and Selectors (BT-4567)

An actor holding secrets (tokens, PKCE verifiers, passwords) can keep them out of OTP status output and crash reports by declaring them with two class-side methods:

Actor subclass: SessionStore
  state: verifier :: String | Nil = nil

  /// State slots redacted in the formatted state of status and crash reports.
  class secretState -> List(Symbol) => #(#verifier)

  /// Messages whose arguments and replies are redacted in formatted status, sys logs and crash reports.
  class secretSelectors -> List(Symbol) => #(#create:boundTo:, #consume:boundTo:)

Every actor has a compiled format_status/1 that applies the declarations:

WhereWhat is redacted
sys:get_status state, and a crash report's stateeach secretState slot's value becomes "[redacted]"; other slots are unchanged
a crash report's last messagea send of a secretSelectors selector keeps its selector, but its arguments become "[redacted]" (also for perform: of that selector)
sys:get_status logged events and a crash report's log (with sys:log on)incoming secret sends, the reply to a secret call, and the state in each entry, as above
the separate proc_lib crash report a crashing actor also writessecret sends still queued in its mailbox (messages), and in its process dictionary (dictionary) secret-selector entries in the pending continueWith: queue and secret slots in any actor state still held there, redacted as above by a logger filter the runtime installs

Three Class Kinds (ADR 0067)

Beamtalk has three class kinds with distinct data keywords and construction protocols:

Class KindData KeywordSemanticsConstructionInstance Process
Valuefield:Immutable data slots, self.slot := is compile errornew / new: / keyword ctorNo
Actorstate: (permitted, not required)Mutable process state, self.slot := persists via gen_serverspawn / spawnWith:Yes
Object(none)No Beamtalk-managed data; often class-methods-only, but can have instances with runtime-backed state (ETS, handles)Custom constructorsNo
// Value — immutable data, no process (ADR 0042)
Value subclass: Point
  field: x = 0
  field: y = 0

  // Methods return new instances (immutable)
  plus: other => Point new: #{x => (self.x + other x), y => (self.y + other y)}
  printString => "Point({self.x}, {self.y})"

// Actor — process with mailbox
Actor subclass: Counter
  state: count = 0

  // Methods mutate state via message passing
  increment => self.count := self.count + 1
  getCount => self.count

// Object — no Beamtalk-managed data; commonly class-methods-only
Object subclass: MathHelper
  class factorial: n =>
    n <= 1
      ifTrue: [1]
      ifFalse: [n * (self factorial: n - 1)]

Key differences:

AspectValue (Value subclass:)Actor (Actor subclass:)Object (Object subclass:)
Data keywordfield:state:(none — compile error)
InstantiationPoint new or Point x: 3 y: 4Counter spawn or Counter spawnWith: #{count => 0}Not instantiable
RuntimePlain Erlang mapBEAM process (gen_server)Class methods only
MutationImmutable — methods return new instancesMutable — methods modify stateN/A
Message passingN/A (direct function calls)Sync messages (gen_server:call)N/A
EqualityStructural (by value)Identity (by process)N/A
Use casesData structures, coordinates, moneyServices, stateful entities, concurrent tasksFFI namespaces, protocol providers, abstract bases

Class hierarchy:

ProtoObject (minimal — identity, DNU)
  └─ Object (protocol provider — reflection, equality, error handling)
       ├─ Integer, String (primitives)
       ├─ Value (immutable value objects — field:)
       │    ├─ Point, Color (value types)
       │    ├─ Collection(E) (abstract)
       │    │    └─ Set(E), Bag(E), Interval
       │    └─ TestCase (BUnit test base)
       └─ Actor (process-based — state: + spawn)
            └─ Counter, Server (actors)

Why this matters:

Object's Three Roles

Object subclass: cannot have instance data (field: or state: is a compile error). Object serves three purposes:

  1. Protocol provider — common methods inherited by all Value and Actor subclasses: isNil, respondsTo:, printString, hash, error:, yourself, show:, showCr: (debug output to Transcript; replaces the former trace:/traceCr: which are deprecated aliases)
  2. FFI namespace — zero-overhead class-method wrappers around Erlang modules and OTP primitives (e.g., Json, System, File, Ets, Random). No instances, no process
  3. Abstract extension point — framework contracts designed for subclassing, where subclasses define methods but hold no data (e.g., Supervisor, DynamicSupervisor)
// FFI namespace — wraps Erlang modules as class methods
Object subclass: Json
  class parse: str => // ... Erlang FFI
  class stringify: obj => // ... Erlang FFI

// Abstract extension point — designed for subclassing
abstract Object subclass: Supervisor
  childSpecs => self subclassResponsibility

Sendability Tiers (ADR 0103)

Because a BEAM send copies the term, whether a value survives crossing a process boundary depends on its class kind. The type checker derives a sendability tier for every inferred type and warns (advisory only, per ADR 0100) when a value's tier is too weak for the boundary it crosses. No new annotations are required for the common case — the class kind is the annotation.

TierWhat it isBoundary behaviour
SendableValue kinds, primitives, symbols, Referencecopies perfectly — always fine
SendableRefActor kinds and the builtin Pidcopies the reference; identity preserved (hover-visible; no v1 diagnostic)
HandleScoped(#scope)Object kinds wrapping a scoped runtime handle#process handles warn when sent; #node handles are silent in v1
UnknownDynamic / untyped FFI / unclassified Objectsilent (nothing to grade on)

A Value composes structurally, inheriting the weakest tier of its fields, and generic collections inherit their element tier (List(Port) is HandleScoped). The builtin table classifies the canonical hazards directly: Pid → SendableRef, Port/FileHandle → HandleScoped(#process), Reference → Sendable, Subscription → HandleScoped(#node).

Checked boundaries (a HandleScoped(#process) value warns): actor message arguments, spawnWith: initial-state maps, blocks sent to actors (including Timer every:do: and postfix ! casts), and Announcement payloads. Local blocks (do:, collect:, ifTrue:) and self-sends do not warn.

Declaring handle scope

A user Object subclass: that wraps runtime state may declare its scope with a class-side handleScope: clause. The value is symbol-valued and the set is open (#process and #node ship first); undeclared Object kinds stay Unknown (silent).

// node-global handle: fine to send within the node, not across nodes
sealed typed Object subclass: MetricsTable
  handleScope: #node

handleScope: is only meaningful on Object-kind classes (a Value/Actor declaration is an advisory no-op). A companion lint nudges FFI-wrapping (native:) Object classes that carry instance behaviour but declare no scope. Suppress a sendability finding with @expect sendability.

Header clauses are parsed in a fixed order — write them as: modifiers → Superclass subclass: Name(TypeParams) → native: module → handleScope: #scope. In particular native: must precede handleScope:; reversing them (handleScope: #process native: pb) silently drops the native: clause (it falls into the class body).

Wrong Keyword Errors

The compiler enforces keyword/class-kind rules with clear error messages:

// state: on a Value — compile error
Value subclass: BadValue
  state: x = 0
// error: use 'field:' for Value subclass data declarations, not 'state:'

// field: on an Actor — compile error
Actor subclass: BadActor
  field: x = 0
// error: use 'state:' for Actor subclass data declarations, not 'field:'

// Any data declaration on an Object — compile error
Object subclass: BadObject
  state: x = 0
// error: Object subclass cannot have instance data declarations;
//   use 'Value subclass:' for immutable data or 'Actor subclass:' for mutable state

Class Modifiers

Class definitions support optional modifier keywords before the superclass:

ModifierMeaningExample
sealedCannot be subclassed by user codesealed Object subclass: Stream
abstractMust be subclassed; cannot be instantiated directlyabstract Object subclass: Supervisor
typedAll fields and methods require type annotations (ADR 0025)typed Actor subclass: TypedAccount

Modifiers can be combined: sealed typed Collection subclass: Array.

Most stdlib classes are sealed — this prevents user code from subclassing built-in types like Integer, String, Array, Result, and Stream. If you need custom behaviour, compose with these types rather than subclassing them.

Method-level sealed. A sealed method cannot be overridden in a subclass. Write it only in a class that can be subclassed (an open or abstract class), where it protects one method of an otherwise extensible class: sealed area => ... or class sealed make => .... In a sealed class that is not abstract it is redundant: the class cannot be subclassed, so none of its methods can be overridden. Every method of such a class counts as sealed whether or not it carries the keyword (class metadata, beamtalk doc and hover report it as sealed), and beamtalk lint reports the keyword as redundant `sealed` (suppress with @expect lint). An abstract sealed class (the stdlib's Boolean, which has the internal subclasses True and False) is exempt from both rules: only the methods that carry the keyword are sealed, and the lint stays quiet.

Performance: Sealed actor classes benefit from a direct-call optimization — self-sends within the class emit direct function calls instead of dynamic dispatch, since the compiler knows no subclass can override the method. This is automatic and requires no user intervention.

Self-Sends and Overrides (BT-3666)

A self send is late-bound on the receiver, as in every Smalltalk: an inherited (or trait-flattened, ADR 0127) method that does self foo runs the foo of the receiver's class, so a subclass override is reached. This is what makes the template-method pattern work.

Actor subclass: Report
  title -> String => "Report"
  render -> String => "== " ++ self title ++ " =="

Report subclass: SalesReport
  title -> String => "Sales"

// SalesReport spawn render  => "== Sales =="

This holds for instance-side sends on actors and value classes, for class-side sends (class foo / self foo inside a class method), and for a protocol's provided methods flattened into a class whose subclass overrides a required selector.

super is the exception by design — it is always bound to the superclass of the class that contains the method. A sealed class cannot be subclassed, so its instance-side self-sends are compiled as direct calls (no lookup); class-side self-sends take the guarded direct call described below, sealed or not. Inside a class method, super foo resolves against the superclass's class methods (the metaclass chain), not its instance methods, and the compiler checks it there: a selector only the superclass's instances understand is reported as not understood (BT-4001). The lookup starts at the superclass and never consults the sending class, so super peek: x reaches the superclass's peek:, never the sending class's own; a same-file >> method counts as one of its class's methods, so super finds a superclass method whether its class body or a same-file >> defined it. The superclass method runs with the live receiver. When no class method on the chain answers the selector, self and super sends from a class method fall through to the class object's own protocol (Class → Behaviour → …), exactly as an outside send to the class does: self name, super name and super superclass answer what C name and C superclass answer, for the receiving class (BT-4252).

Implementation notes: an actor self-send dispatches through the module named by the instance's own '__class_mod__' state key (a per-send map lookup); a class-side self-send to a selector the class defines, sealed or not, calls the compiled method directly when the receiver is the defining class and nothing shadows it (beamtalk_class_dispatch:class_self_direct_ok/4), and otherwise walks the class hierarchy from the receiving class (beamtalk_class_dispatch:class_self_send/3). A class-side self-send runs wherever its calling method runs: in the caller unless its selector is process-bound (ADR 0142, ADR 0153). Every path passes the real class reference as self (BT-4037 retired the old nil). Only self foo late-binds. A class literal always denotes that class: naming the class explicitly (Base foo) runs Base's foo with self bound to Base, even inside a class method that a subclass C inherits and is running, exactly as the same send does from anywhere else and as in Smalltalk. So inside foo, self name answers #Base, and Base new builds a Base; self sends nested inside it late-bind from Base, not C (BT-4317). When the running receiver is Base itself, the send calls the method directly in the current process, behind the same guard; otherwise it is the ordinary class send to Base: in the caller unless the selector is process-bound. Nothing is threaded through class-side self-sends. A selector declared class sealed cannot be overridden; its sends compile to the same guarded direct call as any other own selector.

Cost: every non-sealed actor self-send does a maps:get('__class_mod__', State, Module) lookup (tens of nanoseconds). A class-side self foo is a guarded direct call, sealed or not: when the receiver is the defining class itself and no runtime-installed method (ADR 0084) shadows foo, it calls the compiled class_foo directly after one persistent_term read of the shadow flag (class_self_direct_ok/4); when the receiver is a subclass it walks the class hierarchy (microseconds). Sealing the class or the selector no longer changes this (ADR 0142).

Value subclass: in Depth

Value subclass: defines an immutable value object. All slots are set at construction time; there is no mutation.

Construction forms

Three forms create instances — all produce equivalent results:

// 1. new — all slots get their declared defaults
p := Point new                       // => Point(0, 0)

// 2. new: — provide a map of slot values; missing keys keep defaults
p := Point new: #{#x => 3, #y => 4}  // => Point(3, 4)

// 3. Keyword constructor — auto-generated from slot names
p := Point x: 3 y: 4                 // => Point(3, 4)

The keyword constructor form (Point x: 3 y: 4) is preferred for readability. The argument order follows the order the slots were declared.

with*: functional setters

Each slot automatically gets a with<SlotName>: method that returns a new instance with that slot changed. The original object is unchanged.

p  := Point x: 1 y: 2
p2 := p withX: 10       // new object: x=10, y=2
p  x                     // => 1   (original unchanged)
p2 x                     // => 10
p2 y                     // => 2

// Chaining
p3 := (Point new withX: 5) withY: 7   // x=5, y=7
p4 := Point new withX: 5 |> withY: 7  // the same, as a pipeline

Chain with*: setters by nesting or with a pipeline (|>), not with a cascade: p withX: 5; withY: 7 sends both messages to p and keeps only the last update (see Cascades).

The with<SlotName>: selector is built by uppercasing only the first letter of the slot name. Two slots whose names differ only by the case of their first letter (e.g. x and X) would generate the same setter selector — this is a compile error:

// Compile error — rejected before the code runs:
// Value subclass: Weird
//   field: x = 0
//   field: X = 0   ← error: both `x` and `X` produce the setter `withX:`

Immutability enforcement

Direct slot mutation is illegal in value types:

// Compile error — rejected before the code runs:
// Value subclass: BadPoint
//   field: x = 0
//   badSetX: v => self.x := v   ← error: Cannot assign to slot

// Runtime error:
p := Point x: 1 y: 2
p fieldAt: #x put: 99   // raises: immutable_value

Value equality

Value objects compare by structural equality: two objects with the same class and the same slot values are equal (==).

p1 := Point x: 3 y: 4
p2 := Point x: 3 y: 4
p1 == p2    // => true

p3 := Point x: 9 y: 9
p1 == p3    // => false

// with*: result equals a freshly constructed object
(p1 withX: 10) == (Point x: 10 y: 4)   // => true

This compares the representation, and cannot be changed: the equality operators are not overridable (see Equality operators cannot be overridden). A value type whose logical value differs from its stored form — one that is not canonicalised, or that carries a field outside its identity — should override equals: and say so in its class documentation.

Value objects in collections

Value objects work seamlessly with all collection methods:

points := #((Point x: 1 y: 1), (Point x: 2 y: 2), (Point x: 3 y: 3))

// collect: transforms elements
points collect: [:p | p x]           // => #(1, 2, 3)

// select: filters elements
points select: [:p | p x > 1]        // => #(Point(2,2), Point(3,3))

// inject:into: folds
points inject: 0 into: [:sum :p | sum + p x]   // => 6

Reflection

p := Point x: 3 y: 4
p fieldAt: #x          // => 3
p fieldAt: #y          // => 4
p fieldNames size      // => 2  (contains #x and #y; order is not guaranteed)
p class                // => Point
Point superclass       // => Value

// Full chain from self up to (and including) Object (or Object class for metaclass receivers)
Counter superclassChain        // => [Counter, Actor, Object]
Object superclassChain         // => [Object]
Counter class superclassChain  // => [Counter class, Actor class, Object class]

Message Sends

// Unary message
counter increment

// Binary message (standard math precedence: 2 + 3 * 4 = 14)
2 + 3 * 4

// Keyword message
dict at: #name put: "hello"

// Cascade - multiple messages to same receiver
Transcript show: "Hello"; cr; show: "World"

// Pipeline - each message to the previous result
(Point x: 1 y: 2) withX: 5 |> withY: 10

Cascades

A cascade sends every message to the same receiver and answers the last message's result:

Transcript show: "Hello"; cr; show: "World"
// ≡  Transcript show: "Hello".  Transcript cr.  Transcript show: "World"

The cascade's receiver is the receiver of its first message, and ; fans out to it whatever it is: an actor, a value, a class, an Erlang term or a Dynamic value. That is the right meaning for anything whose messages act on the receiver in place, such as an actor, a ClassBuilder, an Ets table or Transcript.

Each cascade part after a ; is exactly one message. A further message on the same line, as in x foo; size reversed, is a parse error rather than a send to size's result: write (x size) reversed, or put the next statement on a new line (BT-4508).

A cascade on a value drops every update but the last. A value's "update" messages (with*: setters, Dictionary at:put:, Integer max:) answer a new value and leave the receiver alone. A cascade sends the next message to the original receiver, not to that new value, so the earlier results are thrown away:

p := Point x: 1 y: 2
p withX: 5; withY: 10      // => Point(x: 1, y: 10), the withX: result was dropped
p withX: 5 |> withY: 10    // => Point(x: 5, y: 10), the pipeline sends withY: to the copy

To chain messages on the previous result, use a pipeline (|>), the nested form (p withX: 5) withY: 10, or temp locals.

The compiler warns about this shape with cascade-drops-update (ADR 0145 § 3), at each dropped message:

warning: the result of `withX:` is discarded
  note: `Point` is a value: `withX:` answers a new value and leaves the receiver
        unchanged, and a cascade sends `withY:` to the receiver, not to that result
  help: to send `withY:` to the result, use a pipeline: `p withX: … |> withY: …`

It fires only when all of these hold:

Dynamic and union-typed receivers, actors, Object instances, messages that answer some other type (printString, size) and methods inherited from Object (yourself, show:) stay silent. REPL bindings carry no static type, so a cascade on a REPL variable does not warn; the same cascade inside a method with a typed parameter does. When the next message is binary, the help suggests the nested form instead, because a pipeline stage cannot start with a binary message.

A cascade that fans out on a value on purpose (for a side effect of each message) can keep its meaning: silence one with @expect cascade_drops_update on the statement, or a whole package with cascade-drops-update = "off" under [diagnostics] in beamtalk.toml:

@expect cascade_drops_update
0 max: 1; max: 2

The same bug without a cascade is a statement whose copy nobody uses. A non-final statement that is a plain send on a value receiver answering an updated copy (p withX: 5. on its own line) leaves p unchanged, so the discarded-update warning flags it with the same predicate (BT-4522): the result of `withX:` is discarded, with the help "assign the result (p := p withX: …) or chain with |>" (a receiver that cannot be reassigned, such as self, gets "use the result (assign it, return it, or pass it on)"). The last statement of a body or block is its value and is never flagged, nor is a send whose result is used (assigned, passed, returned, or the receiver of another send). A pipeline statement is flagged once, at its last stage. A cascade statement keeps cascade-drops-update, so no span is reported twice. Binary sends are flagged too, except pure ones such as n + 1. on plain operands, which keep the effect_free lint. Dynamic and union receivers, actors and non-value classes stay silent. A method whose body answers its own receiver on every path (BT-4739) is not an update either: a value cannot mutate itself (TestCase can assign its own slots, so a body with self.x := … always counts as an update), so store: v, send: data or checkHeaders: h that ends in self (or ^ self) works through a side effect or only to raise, and a call to it is never flagged unless a subclass override supplies the same selector with a body that does not answer its receiver: the call may then reach an update, so it warns (BT-4788). Every ^ in such a body must return self or raise (^ self error: "…"). A method that ends in a new value (self withX: 1), has a ^ that answers something else, or is a bare @primitive still counts as an update. To discard a result on purpose, assign it to an underscore-prefixed local (_ := p withX: 3.); an assigned result is never flagged. Silence one with @expect discarded_update, or a package with discarded-update = "off" under [diagnostics].

Pipelines (|>) (ADR 0145)

The pipeline operator |> sends each message to the previous result. recv m1 |> m2 |> m3 is exactly ((recv m1) m2) m3, and is defined by that rewrite: there is no new runtime behaviour, the compiler sees the nested sends, and it works the same on values, actors and Dynamic receivers. It is the chaining counterpart of the cascade's fan-out (ADR 0145):

p := Point x: 1 y: 2
p withX: 5 |> withY: 10            // => Point(x: 5, y: 10), same as (p withX: 5) withY: 10

// Collection pipelines
#(1, 2, 3, 4) select: [:x | x isEven]
  |> collect: [:x | x * 10]
  |> inject: 0 into: [:sum :x | sum + x]   // => 60

// Mixed unary and keyword stages
#{#b => 2, #a => 1} |> keys sort |> at: 1   // => #a

A deep chain of functional updates no longer needs nested parentheses:

// Before
self store: ((((st withWebsock: websock)
  withWebsockState: websock)
  withWebsocketOptions: opts)
  withRespState: #upgraded)

// After
self store: (st withWebsock: websock
  |> withWebsockState: websock
  |> withWebsocketOptions: opts
  |> withRespState: #upgraded)

Stages

The part before the first |> is an ordinary expression (recv m1, or just recv: st |> withX: 1 is st withX: 1). Each stage after a |> runs up to the next |> or the end of the expression, and is parsed as an ordinary keyword expression whose receiver is the previous stage's value:

stage := unary-message+ binary-tail? keyword-message? | keyword-message

So a stage is a whole message chain, not one message. Each one means exactly what the same text means with the previous value written in front of it:

StageMeans
x |> keys sort(x keys) sort
x |> sort at: 1(x sort) at: 1
x |> size + 1(x size) + 1
x |> inject: 0 into: [...]x inject: 0 into: [...]

This differs from a cascade part, which is a single message. |> binds looser than keyword messages, like ;. A stage the previous result does not understand raises does_not_understand, exactly as the nested form would, and the type checker reports it at that stage. Reflected source ((MyClass >> #sel) source) and beamtalk fmt keep the |> as written.

Where |> is allowed

A pipeline may appear anywhere a full keyword expression parses: a statement, the right-hand side of an assignment, a ^ value, inside parentheses (and so in a block body), in string interpolation ("total: {orders select: [...] |> size}"), in a match: arm body, in a map value, and in a list, array or tuple literal element.

The one place that needs parentheses is a keyword argument, which is parsed at binary level for every keyword message:

d at: #k put: (p withX: 1 |> withY: 2)   // the pipeline is the argument
d at: #k put: p |> withY: 2               // sends withY: to the result of at:put:

Map keys also need parentheses, as they do for any keyword message.

Errors

CodeError
p withX: 5 |> withY: 10; withZ: 3cannot mix cascade ; and pipeline |> in one expression; parenthesise the part you mean
p withX: 5 |> (end of input)expected a message after |>
p withX: 5 |> 10expected a message after |>, with the hint "|> sends a message to the previous result; it does not apply a function"
d at: #k |> + 1a pipeline stage cannot start with a binary message; write (…) + …
p withX: 5 |> withY: 10!Cast (!) has no return value and cannot be used in an expression, with the hint "bind the pipeline's result to a local, then cast to it on the next line"
x := 1. |> negated (a |> where a statement starts, or a leading-|> line typed on its own at the REPL)a statement cannot start with |>

Layout and the REPL

In a source file a line that starts with |> continues the expression above, by the same rule that lets a line starting with a keyword part continue (see Splitting a Message Send Across Lines): |> can never begin a statement, so the continuation is unambiguous.

In the REPL the line above is already complete, and runs, when you press Enter. So at the REPL, either end each line with |> (a line that ends in |> is incomplete, and the REPL waits for the next line), or wrap the whole pipeline in parentheses:

> #(3, 1, 2) |>
.   sort |>
.   at: 1
// => 1
> (#(3, 1, 2)
.   |> sort
.   |> at: 1)
// => 1

A leading-|> line typed on its own at the REPL is the error "a statement cannot start with |>", with a hint that says to do one of these instead.

For Elixir and Gleam users

The value on the left flows into the step on the right, as in Elixir and Gleam. The one difference is where it lands: in Elixir and Gleam it becomes the first argument of a function; in Beamtalk it becomes the receiver of a message. A Smalltalk receiver sits where an Elixir first argument sits, so the shapes line up one for one (each row is a separate stage, not one chain):

ElixirGleamBeamtalk
orders |> Enum.filter(&paid?/1)orders |> list.filter(is_paid)orders select: [:o | o isPaid]
|> Enum.map(& &1.amount)|> list.map(fn(o) { o.amount })|> collect: [:o | o amount]
|> Enum.sum()|> int.sum|> sum
|> Map.put(:a, 1)|> dict.insert("a", 1)|> at: #a put: 1

The function name (Enum.map) becomes a selector on the value (collect:), and the module disappears because the value's class decides which method runs. Idiomatic Beamtalk does not pipe the head: orders select: … already sends to orders, and Elixir needs orders |> Enum.filter(…) only because Enum.filter is a function. There is no capture syntax (Elixir's &, Gleam's _) for putting the value anywhere but the receiver; when it must be an argument, use then:, a temp local or the nested form.

then: — the value as an argument

Object >> then: aBlock answers aBlock value: self, named after Elixir's Kernel.then/2. It puts the piped value somewhere other than the receiver of the next message:

3 then: [:x | x * x]                                     // => 9
#(1, 2, 3) collect: [:x | x * 2] |> then: [:xs | xs size * 10]   // => 30
#(2, 4, 6) |> then: [:xs | xs inject: 0 into: [:a :b | a + b]] |> printString   // => "12"

It is an ordinary message, so it also works without |>. Put |> in front of a then: that follows a keyword message: xs inject: 0 into: [...] then: [...] is one inject:into:then: send. Unlike ifNotNil:, then: is not inlined by the compiler, and it is not sealed. That has these consequences:

Message Precedence (high to low)

  1. Unary messages: 3 factorial
  2. Binary messages: 3 + 4 (with standard math precedence within binary)
  3. Keyword messages: dict at: #name

Parentheses around a send's receiver or argument only group: when they are redundant they mean nothing, so (self) foo, (MyClass) + 1 and xs do: ([:x | t := t + x]) compile and run exactly like self foo, MyClass + 1 and xs do: [:x | t := t + x]: the compiled behaviour is the same with or without them. Reflected method source ((MyClass >> #sel) source) is the text as written and keeps them — a method written summed: a => (a * 2) + 1 reflects as exactly that — so the IDE method editor shows what is on disk. Source files are never rewritten to drop them: beamtalk fmt, and a workspace flush of a method edited in the REPL or IDE, keep the parentheses as written.

The exception is super, which is not a value: it only names where a send's method lookup starts, so it is valid only as the direct receiver of a message (super printString, super at: 1 put: x, (super printString) size). Every other use is a compile error inside a method body, instance or class side: (super) printString, x := super, ^ super, super as an argument or a collection element, super.count (fields are read through self), and a cascade on super (super a; b; send each message to super separately). To use the receiver itself as a value, write self (BT-4251, BT-4258). A cast to super (super foo!) is a compile error too: super runs the parent class's method in the current process, synchronously, so there is no mailbox to post to. Send it without !, or cast to self (self foo!) (BT-4318).

Splitting a Message Send Across Lines

A newline acts as a statement separator (see "Core Syntax" above), so whether a message send can be split across lines — receiver on one line, message on the next — depends on whether the following line could validly begin a new statement on its own:

// Keyword messages split fine: a bare keyword part (`copyFrom:`) can never
// start a statement on its own, so it unambiguously continues the receiver
// above, no matter how it's indented.
result := "abc"
  copyFrom: 1
  to: 2

// A unary selector chained after something else on the same line also
// splits fine, because only the *continuation* keyword moves to its own line:
result := "abc" asList
  collect: [:ch | ch uppercase]
// A unary selector alone on its own line, immediately after its intended
// receiver, does NOT continue it — it parses as a new statement instead:
result := "abc"
  asList        // parsed as its own statement, not `"abc" asList`

This is intentional, not a bug: a bare identifier like asList is itself a valid statement (e.g. a variable reference), so the parser cannot safely rejoin it with the line above without risking silently swallowing a genuinely separate statement that happens to start with a unary-looking name. Keyword parts don't have this ambiguity — bar: alone can never be a complete statement — which is why only keyword-message continuation is safe to infer automatically.

Keep a unary selector on the same line as its receiver. If the identifier that follows fails to resolve, the diagnostic hints at this — join the two lines instead of chasing a phantom spelling mistake.

Binary Operators

Binary operators follow standard math precedence (highest to lowest):

Exponentiation (highest precedence)

Multiplicative

Additive

Number-on-the-left coercion (plusFromNumber: etc.)

+ - * / are receiver-dispatched messages, so a value type can overload them as the receiver — aVector + 5 works because Vector defines +. That says nothing about 5 + aVector: a numeric literal (or other statically-numeric receiver) on the left, with a non-numeric value type on the right. For that shape, Beamtalk dispatches to a reflected method on the right operand instead of crashing, named by a <verb>FromNumber: convention:

OperatorReflected method
+plusFromNumber:
-minusFromNumber:
*timesFromNumber:
/divFromNumber:
<lessThanFromNumber:
<=lessOrEqualFromNumber:
>greaterThanFromNumber:
>=greaterOrEqualFromNumber:

The four comparison selectors follow the same convention with their own guidance (see Comparison below). A value type opts in per operator by declaring the method it wants to support, alongside its ordinary receiver-dispatch operators:

Value subclass: Vector
  field: components :: Array = #()

  + other :: Number -> Vector => self collect: [:c | c + other]
  - other :: Number -> Vector => self collect: [:c | c - other]

  plusFromNumber:  n :: Number -> Vector => self collect: [:c | n + c]
  timesFromNumber: n :: Number -> Vector => self collect: [:c | n * c]
  minusFromNumber: n :: Number -> Vector => self collect: [:c | n - c]
aVector + 5   // => Vector(6, 7, 8)   receiver-dispatch `+`, unchanged
5 + aVector   // => Vector(6, 7, 8)   dispatches to `aVector plusFromNumber: 5`

Operand order matters — easy to get backwards for a non-commutative operator. The reflected method's receiver (self) is the value that was on the right of the original expression; its parameter is the value that was on the left. 5 - aVector sends aVector minusFromNumber: 5, computing n - self (5 minus each component) — not self - n. aVector - 5 (ordinary receiver-dispatch -, unchanged) computes the opposite: each component minus 5. These are genuinely different computations, not the same subtraction read backwards:

aVector := Vector withAll: #(1 2 3)
aVector - 5   // => Vector(-4, -3, -2)   each component minus 5 (self - n)
5 - aVector   // => Vector(4, 3, 2)      5 minus each component (n - self)

When an operator doesn't apply, implement it anyway — to reject with intent. Not every reflected operator makes sense for every type: 5 / aVector ("a number divided by a vector") rarely has an obvious meaning the way 5 * aVector (scale) does, and a point-like type (e.g. Temperature) may sensibly support + but not *. Omitting the method leaves does_not_understand to fire on a selector — divFromNumber: — that the caller never typed, which is harder to connect back to their own 5 / aVector than an ordinary DNU is. Implementing the method anyway, with a body that rejects explicitly, is better:

divFromNumber: n :: Number -> Vector =>
  self error: "Cannot divide a number by a Vector — did you mean (aVector / n)?"

A type author who commits to number-on-the-left arithmetic at all typically implements all four reflected methods — some as real arithmetic, the rest as deliberate rejections — not a variable subset.

Missing hook: does_not_understand, with a hint. A type that implements no reflected method at all still fails safely — 5 + aThing raises an ordinary does_not_understand rather than crashing with a raw BEAM badarith. Because plusFromNumber: is a selector synthesized by this mechanism rather than one the caller ever typed, the error carries an added hint naming the original operator:

5 + "not a vector"
// => ERROR: String does not understand 'plusFromNumber:'
// => ERROR: '+' cannot combine a number with String — the right operand must be a number, or a value whose class implements 'plusFromNumber:'

This is receiver-dispatch's mirror image, not a new arithmetic mechanism: no generality/coercion tower, no perform:-based reflective retry — each reflected method is an ordinary, fully-typed method, so static typing (covariant-return refinement) and compile-time DNU checking work on it exactly as they do on +/-/*// themselves. A type that never implements number-on-the-left arithmetic pays no cost for it: a statically-typed call site (total + delta, both operands' types known at compile time) compiles to the identical bare arithmetic instruction whether or not this mechanism exists. The comparison operators (< > <= >=) take the same convention, with their hooks above; see Comparison. See ADR 0116 for the full double-dispatch design, the rejected alternatives (a Smalltalk-style generality tower, perform:-based retry), and the zero-cost measurement for the statically-typed case.

Comparison

Comparisons are messages sent to the receiver, which decides. Integer, Float, Character, String and Symbol define them (numbers numerically, characters by codepoint, strings and symbols by codepoint, lexicographically); a value type can define its own (aMoney < bMoney reaches Money>><). A receiver whose class defines no ordering raises does_not_understand — including the non-object primitives nil, true/false, lists and tuples, and a raw Binary (a bare BEAM binary; a String is the tagged string term at run time, so it reaches String>><, BT-5261):

#apple < #banana   // => true
x := nil
x < 5              // => ERROR: UndefinedObject does not understand '<'

This holds however the receiver is typed: an untyped local or parameter, an :: Integer | Nil field that holds nil, or an :: Integer parameter or field that was handed a wrong value. A declared type is not enforced at run time (a Dynamic argument, an FFI result or a cast can violate it), and the BEAM's < is a total order that never raises, so trusting a declaration would answer nil > 10 with true. Only a receiver whose kind the compiler proves (a literal, self in Integer/Float/Character/String) compiles to the bare comparison instruction. Every other receiver is checked at run time with one inline type test: a :: Integer-style or :: String parameter or field is tested for its declared kind, anything else for a number or character. A receiver that fails the test is sent the operator as a message, so it raises does_not_understand (or reaches its own overload). There is no "total order over every value" to fall back on.

==, =:=, /= and =/= are unaffected: Erlang equality never term-orders, so a wrong-kind value answers false (true for the inequalities), not a wrong ordering.

A number on the left orders only against a number (ADR 0116 addendum, BT-5176). When the receiver of <, <=, > or >= is a number (an Integer, a Float, or a Character, which is a codepoint) and the argument is not, the argument is sent a reflected hook, with the number as its parameter, the way 5 + aVector sends plusFromNumber::

ExpressionSent to the right operandThe hook answers
n < xx lessThanFromNumber: nn < x
n <= xx lessOrEqualFromNumber: nn <= x
n > xx greaterThanFromNumber: nn > x
n >= xx greaterOrEqualFromNumber: nn >= x

This covers every send: an inlined 5 < x, perform:, and the methods built on the four operators (max:, min:, between:and:). An argument whose class has no hook raises does_not_understand for the hook, with a hint naming the operator typed, instead of answering by the BEAM's term order (3 <= nil used to be true, 3 max: nil used to be nil):

3 <= nil
// => ERROR: UndefinedObject does not understand 'lessOrEqualFromNumber:'
// => ERROR: '<=' cannot order a number against UndefinedObject — the right operand must be a number, or a value whose class implements 'lessOrEqualFromNumber:'

aMoney := (Money new) withCents: 500   // Money as defined below
499 < aMoney     // => true    (aMoney lessThanFromNumber: 499)
3 == nil         // => false   (equality stays total)
nil < 3          // => ERROR: UndefinedObject does not understand '<'

nil < 3 and 3 < nil now fail the same way, so one on: RuntimeError do: handler covers both (and 3 + nil).

Collection max / min follow the same rule: all numbers, all Strings or all Symbols compare natively, and any other mix is folded pairwise with the dispatched > / <, so #(3, nil) max raises as 3 max: nil does. A value type that should compare with numbers implements the hooks:

Value subclass: Money
  field: cents :: Integer = 0

  < other :: Money -> Boolean => self.cents < other cents   // aMoney < bMoney

  lessThanFromNumber:       n :: Number -> Boolean => n <  self.cents
  lessOrEqualFromNumber:    n :: Number -> Boolean => n <= self.cents
  greaterThanFromNumber:    n :: Number -> Boolean => n >  self.cents
  greaterOrEqualFromNumber: n :: Number -> Boolean => n >= self.cents

Only an argument the compiler proves is a number (a number or character literal, self in Integer/Float/Character) skips the test; a declared argument (n :: Integer) is tested, since a declaration is not enforced at run time.

A String or Symbol on the left orders only against its own kind (BT-5213). Any other argument raises a type_error (TypeError) naming both classes. There is no hook to implement, unlike the number side, and a Symbol does not order against a String (or the reverse), although both have text:

"apple" < "banana"   // => true
#apple < #banana     // => true
"a" < 5
// => ERROR: String>><: cannot order a String against Integer
// => ERROR: '<' cannot order a String against Integer — the argument must be a String
#a <= nil
// => ERROR: Symbol>><=: cannot order a Symbol against UndefinedObject
// => ERROR: '<=' cannot order a Symbol against UndefinedObject — the argument must be a Symbol
#a < "a"             // => ERROR: TypeError (convert first: #a asString < "a")

This covers every send, inlined or dynamic (perform:). A Character argument is named Integer in the error, since a Character is a codepoint integer at run time. Only a String argument the compiler proves (a String literal, self in String) skips the test. Default sort and Dictionary/Set order still use the BEAM's term order, so a mixed list sorts without raising. The compiler warns when it can see a mismatch (the argument's static type is known and is not the receiver's kind, e.g. 5 < nil, #a < 5); an untyped or generic argument stays silent. The warning is stricter than the run-time rule for Character: $a < 1 is warned about, but at run time it orders the codepoint numerically.

Arithmetic and comparison on fields: annotate numeric state

Arithmetic and comparison operators are messages, so self.count + 1 must dispatch to the object's + when count holds a Point or Money. The compiler emits the bare Erlang arithmetic instruction only when it knows the operand is a primitive; otherwise it adds a runtime type test that sends the message to objects. For a field, "knows" means the declared type: a field annotated :: Integer, :: Float or :: Number takes the bare fast path for arithmetic. A comparison is bare only on a receiver the compiler proves (a literal, self in a builtin class); on a field declared :: Integer, :: Float, :: Number, :: Character or :: String it gets one inline test for the declared kind, because a declaration is not enforced at run time (BT-4823; see Comparison above). A union with Nil (:: Integer | Nil) stays bare for arithmetic only; its comparisons get the general runtime test so a nil raises instead of term-ordering. An untyped field always gets the runtime test, whatever its default, because writers outside the class can store any object in it (BT-3925):

Actor subclass: Counter
  state: count = 0                       // untyped: guarded
  increment => self.count := self.count + 1

c := Counter spawnWith: #{#count => aPoint}
c increment                              // sends Point>>+, no badarith

Actor subclass: FastCounter
  state: count :: Integer = 0            // annotated: bare arithmetic
  increment => self.count := self.count + 1

The test is cheap (the BT-3925 counter benchmark measured no slowdown, see docs/development/benchmarks.md), but annotating numeric state with :: Integer is the documented way to get the bare instruction.

Equality (lowest precedence)

Note: bare = is not a valid Beamtalk operator — it has no entry in the parser's precedence table, so x = y fails to parse. Use =:= for value equality or == for reference equality.

Equality operators cannot be overridden

Unlike the arithmetic (+ - * /) and ordering (< > <= >=) operators, which are dispatched as messages so a value type can overload them, all four equality operators are lowered directly to the corresponding Erlang BIF at codegen time (ADR 0002). There is no method lookup, so a class-level =:= / =/= / == / /= method could never be called. Declaring one is a compile error (BT-2997). A dynamic send — x perform: #'==' withArguments: #(y), x respondsTo: #'==' — works on every receiver (integers, pids, references, value objects, actors): it reaches ProtoObject's declarations, whose bodies are the same BIFs (BT-3919).

Value subclass: Money
  field: cents :: Integer = 0
  =:= other :: Money -> Boolean => self.cents =:= other cents
  // error: `=:=` cannot be overridden — this method can never be called

Use equals: instead. It is declared on Object, defaults to =:=, and is an ordinary message send, so overriding it works:

// Fractions stored unnormalised: 1/2 and 2/4 are different terms…
half := Fraction numer: 1 denom: 2
twoQuarters := Fraction numer: 2 denom: 4

half =:= twoQuarters      // => false  (structural — compares representation)
half equals: twoQuarters  // => true   (dispatches to Fraction>>equals:)

This is a deliberate limit, not a gap to be closed. The keyed containers decide identity inside the VM, below anything the language can dispatch — Dictionary by Erlang map keys, Set by a term-order-sorted list — as do lists:member/2, ets, and receive-pattern matching. An override the compiler honoured would still be invisible to all of them, so a =:= b could report true while a Set holding both still reported size 2. A class that needs content-based membership must normalise its representation rather than redefine the operator.

Both containers use =:= for identity, so they agree with each other and with List>>includes: — Set new add: 1; add: 1.0 holds two elements, matching a Dictionary keyed on 1 and 1.0. What they cannot do is consult a user-defined equals:.

What honours equals:
Compares with
includes: on Collection, List, Array, Dictionary (searches values); List>>indexOf:; TestCase>>assert:equals:equals:
Set elements, Dictionary keys, List>>unique, List>>withoutDuplicatesBy: keys=:=

The line is searching versus keying: a linear search can afford to ask each element, while membership in a keyed container — or deduplication — needs an order or a hash that a user-defined equals: cannot supply. This is the same constraint Java's equals/hashCode contract expresses.

An equals: override must agree with =:= wherever =:= holds: it may only make more values equal, never fewer. The searches rely on that to try raw equality first and dispatch only on a miss, and so does an equals: send to a primitive receiver (Integer, Binary, String, Symbol, …): a raw hit answers true without dispatch, and a raw miss answers false without dispatch unless the receiver's class chain overrides equals:.

Where the two notions of equality are genuinely different questions, prefer a domain-specific name to overriding equals: — DateTime keeps equals: structural and offers sameInstant: for instant-based comparison.

Short-circuit boolean operators (and:/or:)

and and or are not binary operators. They are keyword messages that take blocks for short-circuit evaluation:

// Short-circuit AND - second block only evaluated if first is true
result := condition and: [self expensiveCheck]

// Short-circuit OR - second block only evaluated if first is false  
result := condition or: [self fallbackValue]

Field Access and Assignment

Direct field access within actors using dot notation:

// Read field
current := self.value

// Write field
self.value := 10

// Explicit assignment
self.value := self.value + 1
self.count := self.count - delta
self.total := self.total * factor

Note: self.field compiles to direct map access, not a message send. For external access to another actor's state, use message sends.

Parenthesized assignment: A field assignment used as an operand (the receiver or argument of a send, an element of a literal, an assigned value) must be wrapped in parentheses. There, (self.x := 5) answers the assigned value:

// Assignment as expression (returns 6)
(self.x := 5) + 1

// Field assignments as sequential statements
self.x := 5
self.y := self.x + 1
self.y

Parentheses only matter in operand position. Around a whole statement they change nothing. In a value-type method, a trailing field assignment answers the updated self whether or not it is parenthesised: (self.x := 5) and self.x := 5 as the last statement both answer the updated self. To answer the assigned value, write it explicitly (BT-4092):

// Value-type method answering the updated self (with or without parentheses)
withX5 =>
  self.x := 5

// Value-type method answering 5
setXTo5 =>
  self.x := 5
  5

Before BT-4092, a parenthesised trailing field assignment answered the assigned value.

Limitation: In an actor instance method a block reads and writes the actor's fields live, wherever it is made and run (see Actor Blocks See Live State). In a value-type method, field assignments (self.x :=) in stored closures are still a compile error — they require control-flow context for state threading. A closure that assigns an outer local may not be stored at all: a block may assign a captured variable only where it is written directly as the argument of a control-flow construct or a compiler-known collection message (do:, inject:into:, on:do:, ...), and a block that is stored, returned, placed in a collection literal or passed to any other method is rejected at the assignment (ADR 0133, see What Works and What Doesn't). Have the block answer the new value and assign it where the block is called.

// ❌ ERROR in a value-type method; works in an actor instance method (ADR 0137)
nestedBlock := [:m | self.x := m]

// ✅ Field mutation in control flow blocks
true ifTrue: [self.x := 5]

// ✅ Local variable mutation in a control-flow block
count := 0
10 timesRepeat: [count := count + 1]   // count => 10

Blocks (Closures)

// Block with no arguments
[self doSomething]

// Block with arguments
[:x :y | x + y]

// Block with local variables
[:x | temp := x * 2. temp + 1]

Scoping: a variable first assigned inside a block is local to that block — temp above is invisible outside it — and nested blocks see their enclosing blocks' locals. Assigning a variable declared outside the block (a captured local) is a separate rule: it compiles only where the block is written directly as the argument of a control-flow construct or a compiler-known collection message (see Control Flow and Mutations and ADR 0133).

Non-local returns: ^ inside a block returns from the enclosing method, not just from the block. This is the standard Smalltalk non-local return semantics and enables clean early-exit patterns:

Object subclass: Finder
  firstPositive: items =>
    items do: [:x | x > 0 ifTrue: [^x]]
    nil   // returned only if no positive element found

Object subclass: Validator
  validate: x =>
    x isNil ifTrue: [^"missing"]
    x isEmpty ifTrue: [^"empty"]
    "ok"

^ at the top level of a method body is an early return (the method exits immediately). ^ inside a block argument causes the method to exit with that value.

The type checker checks every ^ — a top-level early return, one inside a block, one in a match arm — against the method's declared return type (BT-5283). That includes a ^ in a block the method returns or stores: ^ always answers the home method, so -> Block with [:x | ^x] where x is an Integer warns that the body returns Integer.

Propagating a Result's error is not a mismatch (BT-5290). Where a Result(T, E) variable x can only be the error variant, the checker treats ^x as Result(Never, E), which fits any declared Result(U, E') whose E' accepts E. So x isError ifTrue: [^x] type-checks in a -> Result(U, E) method for any T and U. The narrowing covers:

It ends at any reassignment of x, including one inside a nested block, and it does not hold anywhere in a block (such as a do: body) that rebinds x, or in any block of a send whose other block (receiver or argument) rebinds it (do:separatedBy:, [...] whileTrue: [...], an on:do: handler that retries), since a later run could return the rebound value. The arms of a two-armed conditional (ifTrue:ifFalse:) are exclusive, so a write in one does not affect the other. Known gap: a block stored earlier and run inside the guarded block (b := [x := ...] before the guard, then b value. ^x inside it) is not seen, so that ^x is still treated as the error variant. It does not reach the rest of the method after the guard. A ^x anywhere else (no guard, isOk ifTrue:, the ifOk: block) is checked with the full Result(T, E) type, so a mismatched success type is still reported. x must be a local: self.res isError ifTrue: [^self.res] is not narrowed, because a send in the block could reassign the field. Copy it to a local first (res := self.res). The narrowing only changes how ^x is checked: inside the block x keeps its Result(T, E) type, so x error answers E and x valueOr: d answers T as before. A mismatched error type is reported with the declared success type, e.g. body returns Result(Tuple, String) for a -> Result(Tuple, Integer) method.

A local a loop writes keeps every type the loop can give it, at the loop head as well as after it (BT-5298). A block that may run more than once (a do: or collect: body, both blocks of [...] whileTrue: [...], a block passed to any method that may call it repeatedly) starts each later run with the values an earlier run left in the method's locals, so the checker infers its body with each outer local it writes typed as the join of its type before the block and every type the body leaves it with. In

refused := nil
items do: [:each |
  (refused notNil and: [each =:= "x"]) ifTrue: [^Result error: refused]
  refused := each]

refused is String | Nil at the early return, and notNil narrows it to String, so the method type-checks as -> Result(Integer, String). Two repeatable blocks of one send run interleaved, so each also sees the other's writes: a whileTrue: condition sees its body's, a do:separatedBy: separator sees the body's. If a chain of dependent locals (p := a. a := b. b := c. c := each) is too long for the checker to follow in three passes, the locals still changing enter the block as Dynamic, never narrower than a later run could see. A block that runs at most once per send keeps its plain entry types: the arms of ifTrue:, ifFalse:, ifNil:, ifNotNil: and their two-armed forms, and:, or:, ifOk:, ifError:, ifOk:ifError:, then:, an on:do: or ensure: block and its handler or cleanup, the blocks of the lookups (at:ifAbsent:, at:ifAbsentPut:, at:ifPresent:, at:ifPresent:ifAbsent:, removeKey:ifAbsent:), Result tryDo:, and a block literal receiving value, value: and the rest of that family. A cascade on a block literal ([...] value; value) runs it once per message, so it is repeatable. Annotating the local (refused :: String | Nil := nil) is still allowed and states the same type.

Guard clauses like Validator>>validate: above compile to plain branches, with no non-local-return frame. A method whose only block ^s are early returns from inlined conditionals at its top level (ifTrue:, ifFalse:, ifNil:, ifNotNil: and their two-branch forms) compiles them as if written x isNil ifTrue: ["missing"] ifFalse: [...]. A receiver that turns out not to be a Boolean is still sent ifTrue: with a block that returns from the method. For an ifTrue:/ifFalse: guard whose receiver might not be a Boolean, this holds when the block is just ^ and a literal, a variable or a field of self. Other guard blocks compile this way only when the receiver is a Boolean by construction: true, false, an ==/=:=//=/=/= comparison, or a </>/<=/>= comparison whose left operand is a number, string or character literal or a parameter typed :: Integer, Float, Number, Character or String that the method never rebinds (codegen compiles that comparison to the bare Erlang comparison, which never sends). Any other block ^, including one inside a real closure (do:, detect:, a stored block), needs the non-local-return throw/catch, and the method then compiles every ^ that way.

Abstract and Stub Methods

Empty method bodies are a compile-time error. Use one of these two explicit forms instead:

// Abstract interface contract — must be overridden by subclasses
area => self subclassResponsibility

// Work-in-progress stub — not yet implemented
processPayment => self notImplemented
MethodPurposeError message
subclassResponsibilityAbstract method; subclass must override"This method is abstract and must be overridden by a subclass"
notImplementedWork-in-progress stub"Method not yet implemented"

Both methods raise a runtime error with a clear message. The distinction is intent: subclassResponsibility signals an interface contract, while notImplemented marks incomplete work.

Class-Side Methods (ADR 0048)

Methods prefixed with class belong to the class itself, not to instances. They are called on the class name directly.

Object subclass: MathUtils
  class factorial: n =>
    n <= 1
      ifTrue: [1]
      ifFalse: [n * (self factorial: n - 1)]

  class fibonacci: n =>
    n <= 1
      ifTrue: [n]
      ifFalse: [(self fibonacci: n - 1) + (self fibonacci: n - 2)]

MathUtils factorial: 10    // => 3628800
MathUtils fibonacci: 10    // => 55

Common uses:

error: on a class object. A class object is an Object, so a class with no class-side error: answers error: with Object>>error:: Integer error: "x" raises a user_error (its errorClass is #'Integer class'), whether the class is written literally, held in a variable or reached with perform:, and so does self error: "x" in its class methods. A class that defines a class-side error: (Result class>>error:, Logger class>>error:) receives the send instead, by every route: Result error: #x builds a Result. Inside such a method, self error: m sends to that same class-side error: again, so class error: m => self error: m recurses instead of raising. To raise from it, use super error: m (which reaches Object>>error:) or Error signal: m.

A class has no state (ADR 0153)

A class holds no state. There is no classState:, no late classState: and no self.x in a class method; each is a compile error ("a class has no slots"), with no deprecation period. state: (per-instance actor state) and field: (per-instance immutable data) are the only slots. Pick the replacement by what the state was for:

UseReplacement
Mutable shared state, a singletonA named Actor
A counterAtomicCounter
A cacheEts, or an Actor's state:
A literal constantA class method: class limit => 100
A value that is expensive to buildPersistentTerm at: key ifAbsentPut: [...]

The full old-to-new table is in the CHANGELOG entry for ADR 0153.

A singleton is a named Actor, and current asks the runtime each time it is called:

Actor subclass: Registry
  state: entries = #{}

  class current -> Registry => (self named: #registry) unwrap

  register: key as: value => self.entries := self.entries at: key put: value
  lookup: key => self.entries at: key ifAbsent: [nil]

The application's supervisor starts the actor under that name (a SupervisionSpec with a name), so it is restarted if it dies. In a script or at the REPL, start it once with Registry spawnAs: #registry.

A shared counter is an AtomicCounter, created once and looked up by name from any process:

AtomicCounter new: #ordersCreated    // once, at application start
(AtomicCounter named: #ordersCreated) increment

Programmatic Class Creation (ClassBuilder) (ADR 0038 / ADR 0084)

Object subclass: Counter … is the grammar form, but a class can also be built programmatically by cascading messages to a ClassBuilder and ending with register. This is a first-class user API (the same protocol the compiler emits for the grammar form): register returns the new, dispatchable class object.

// Build a class in one cascade. register returns the canonical class object.
account := Object classBuilder
  name: #Account;
  superclass: Object;
  fields: #{ #balance => 0 };
  methods: #{ #balance => [:inst | inst fieldAt: #balance] };
  classMethods: #{ #open => [:self | 1] };
  register

account new balance        // => 0
Account open               // => 1  (also reachable by name — the name IS the class)

Each block value is compiler-lowered into the same dispatchable fun a file-defined method produces, so super / self resolve — it is not a naive runtime closure. Class methods built this way are callable and reflectable (ADR 0084).

Incremental piece API. A class can be assembled one piece at a time before register — the "browser" use case. The add* setters write the same maps the bulk setters do, and removeMethod: / removeClassMethod: drop a piece:

Object classBuilder
  name: #Tally;
  superclass: Object;
  addField: #count default: 0;
  addMethod: #answer body: [:inst | 42];
  addClassMethod: #tally body: [:self | 15];
  register

Tally new answer           // => 42
Tally tally                // => 15

Instantiation. A purely programmatic (module-less) builder class instantiates with new / new:, exactly like a compiled value type:

point := Object classBuilder name: #P; superclass: Object; fields: #{ #x => 0, #y => 0 }; register
point new: #{ #x => 3, #y => 4 }     // => a P  (fields seeded from the map)

Metadata parity. Optional setters bring a builder-defined class to :help parity with a file-defined one — methodSignatures: / classMethodSignatures:, methodDocs: / classMethodDocs:, methodReturnTypes: / classMethodReturnTypes:, classDoc:, meta:, and isConstructible:. The class-side method bodies are also auto-indexed for SystemNavigation source-text queries.

Class-side live edit. A registered class's class method can be live-edited with the same >> patcher used for instance methods (see Live Patching and Same-File Extension Methods below), e.g. Counter class >> limit => 100. The class-side dispatch path picks up the new class method immediately (ADR 0084). Separately, a runtime class-method fun (a builder classMethods: fun, or one installed from Erlang with beamtalk_object_class:put_class_method/3,4) is removable: X class removeSelector: #sel takes it back and restores the compiled method it replaced, if any (BT-4438; see Removing methods below). This does not apply to a >> live edit like the one above: that recompiles the class, so removeSelector: removes the edited method outright.

The grammar form (Object subclass: …) remains the idiomatic way to define a class in source. The programmatic builder is for tooling, REPL exploration, and metaprogramming where the class shape is computed rather than written out.

Doc Comments (///)

Triple-slash comments (///) are structured documentation parsed into the AST and queryable at runtime via Beamtalk help:. They support Markdown formatting and a ## Examples convention with fenced code blocks.

/// Counter — A simple incrementing actor.
///
/// Demonstrates actor state and message passing.
///
/// ## Examples
/// ```beamtalk
/// c := Counter spawn
/// c increment   // => 1
/// ```
Actor subclass: Counter
  state: value = 0

  /// Increment the counter by 1 and return the new value.
  ///
  /// ## Examples
  /// ```beamtalk
  /// Counter spawn increment   // => 1
  /// ```
  increment => self.value := self.value + 1

Query documentation at runtime:

Beamtalk help: Counter
// => "== Counter < Actor ==\n  increment\n  ..."

Beamtalk help: Counter selector: #increment
// => "Counter >> increment\n  Increment the counter by 1..."

Doc comments flow from source → AST → compiled BEAM module → runtime. They are not stripped at compilation. The ## Examples blocks are the source for Beamtalk help: output and can be verified by the test framework.

Documenting Parameters (## Arguments / ## Options)

The signature carries the declared shape; the /// comment carries the human-readable meaning. Parameter names are inferred from the signature — never repeat them with @param/@returns tags (ADR 0008, Resolved Question 3). Document parameters with conventional Markdown headings:

The recipe for an option list:

  1. Declare a named type alias for the option shape so the signature stays readable.
  2. Type each parameter as name :: Type and give the method a -> ReturnType.
  3. Under ## Options, list one bullet per key with its type and default value.
/// A single fetch option: a key tuple of name plus value.
type FetchOption = Tuple(Symbol, String | Integer | Boolean)

Object subclass: Fetcher
  /// Fetch a URL with options.
  ///
  /// ## Arguments
  /// - `url` (String) — the URL to fetch.
  ///
  /// ## Options
  /// - `#timeout` (Integer, default `5000`) — request timeout in milliseconds.
  /// - `#retries` (Integer, default `3`) — times to retry on failure.
  /// - `#agent` (String, default `"beamtalk"`) — User-Agent header value.
  ///
  /// ## Examples
  /// ```beamtalk
  /// Fetcher fetch: "https://example.com" options: #({#timeout, 1000})
  /// ```
  class fetch: url :: String options: opts :: List(FetchOption) -> String =>
    opts isEmpty ifTrue: [url] ifFalse: [url]

Flag lists. When every option is a bare on/off flag, declare the alias as a union of symbol literals and type the parameter List(Alias). Each bullet under ## Options names one flag; there is no per-flag type or default. The parameter itself is still required — describe the empty case as "pass #() for none", never as a default, and offer a shorter selector without the list when callers commonly pass no flags. Regex class>>from:options: is the stdlib example:

/// A single PCRE compile flag.
type RegexOption = #caseless | #multiline | #dotall | #extended | #ungreedy

sealed typed Value subclass: Regex native: beamtalk_regex
  /// Compile a regex pattern with PCRE options (class method).
  ///
  /// ## Arguments
  /// - `pattern` (String) — the PCRE pattern to compile.
  /// - `opts` (List(RegexOption)) — compile flags; pass `#()` for none.
  ///
  /// ## Options
  /// - `#caseless` — case-insensitive matching.
  /// - `#multiline` — `^` and `$` match at line breaks.
  class from: pattern :: String options: opts :: List(RegexOption) -> Result(Regex, Error) =>
    self delegate

Document the flags once, on the canonical method, and point other methods that take the same alias at it in prose (for example String>>matchesRegex:options: says "See Regex class>>from:options: for the option list") rather than copying the bullets. (Method-level @see Class>>selector is not parsed by the help/LSP/MCP surfaces, so don't use it for this.) When the flags are interpreted by native Erlang code, the runtime's accepted set must be tested against the alias members — beamtalk_regex_tests does this for RegexOption by reading the alias from the stdlib app's type_aliases metadata.

This mirrors the Erlang (-type + -doc), Gleam (///), and Elixir (## Options) idiom: the type alias is the machine-checked shape, the bullet list is the prose. A list literal passed to a List(E) parameter has each element checked against E: options: #(#bogus) warns Element 1 of argument 2 of 'from:options:' on Regex expects RegexOption (…), got #bogus, as does a non-symbol element or a tuple of the wrong shape. Only a list literal written at the call site is checked element by element — a list built at runtime, or held in a variable typed plain List(Symbol), reaches the method unchecked — so the native implementation must still validate what it receives.

Method Category Dividers (// === Name ===)

A // === Name === comment placed between methods introduces a method category — a named group used across all surfaces: the LSP outline (documentSymbol), VS Code breadcrumbs/sticky-scroll, LSP folding ranges (textDocument/foldingRange), REPL :help grouped method listing, and MCP docs structured output.

Value subclass: Point
  field: x :: Integer
  field: y :: Integer

  // === Accessing ===

  /// The X coordinate.
  x -> Integer => self.x

  /// The Y coordinate.
  y -> Integer => self.y

  // === Arithmetic ===

  /// Add two points.
  + other :: Point -> Point =>
    Point x: self.x + other x y: self.y + other y

Format: a leading // line comment whose trimmed text is =+ <name> =+, where the leading and trailing = runs are the same length (3 or more) and <name> is non-empty. Triple-slash (///) comments are not recognized as dividers. A =-bordered comment that looks like a divider but doesn't parse as one (mismatched = run lengths, too-short runs, /// instead of //) is flagged by beamtalk lint as a near-miss (BT-3240). A class with no dividers keeps the existing flat outline — no behavior change.

Methods following a divider belong to that category until the next divider or end of class. Instance-side and class-side methods are merged in true source order (not grouped by side). The REPL falls back to the flat alphabetical listing when grouping can't be trusted (no on-disk .bt file, no dividers, or unflushed >> patches). The stdlib uses this convention throughout (BT-2601, BT-2626, BT-3237, BT-3239, BT-3240).

Erlang FFI

Beamtalk provides direct access to all Erlang modules via the Erlang gateway object (ADR 0028). Send a unary message with the module name to get a proxy, then send messages as normal:

// Call any Erlang module function
Erlang lists reverse: #(3, 2, 1)      // => [1, 2, 3]
Erlang erlang node                     // => current node atom
Erlang maps merge: #{#a => 1} with: #{#b => 2}

// Store a module proxy for repeated use
proxy := Erlang crypto
proxy strong_rand_bytes: 16            // => random binary

The (Erlang module) pattern is used throughout the stdlib to wrap Erlang functions as Beamtalk class methods:

// How File.readAll: is implemented — a thin wrapper.
// The `{ok, _} | {error, _}` tuples beamtalk_file returns become a Result
// at the FFI boundary (see "Result conversion" below), so the return type
// is Result(String, Error), not a bare String.
Object subclass: File
  class readAll: path :: String -> Result(String, Error) =>
    (Erlang beamtalk_file) readAll: path

A class that delegates wholesale to one Erlang module can declare the module on subclass: and replace each body with => self delegate instead of hand-writing the FFI call — see native: for stateless Objects. Stream (native: beamtalk_stream) is the worked example.

Keyword mapping: The Erlang function name is taken from the first keyword (with its colon removed); the remaining keyword values follow as positional arguments. Erlang maps merge: a with: b calls maps:merge(A, B) (not maps:merge_with — only the first keyword names the function). Unary selectors map directly: Erlang erlang node calls erlang:node().

Result conversion (ADR 0076): Erlang functions that return {ok, Value} or {error, Reason} tuples are automatically converted to Result objects at the FFI boundary. This means FFI calls use the same error-handling idiom as native Beamtalk code:

// FFI calls returning ok/error tuples become Result objects
result := Erlang file read_file: "/tmp/hello.txt"
result              // => Result ok: "Hello, world!\n"
result value        // => "Hello, world!\n"

// Use Result combinators directly on FFI returns
result map: [:content | content size]
// => Result ok: 14

// Error path
result := Erlang file read_file: "/nonexistent"
result              // => Result error: enoent
result isError      // => true

// Chain FFI calls with andThen:
(Erlang file read_file: "/tmp/config.json")
  andThen: [:content | Erlang json decode: content]
  mapError: [:e | "Config load failed: " ++ e message]

// Bare ok atoms (e.g. file:write_file/2) become Result ok: nil
Erlang file write_file: "/tmp/out.txt" with: "data"
// => Result ok: nil

Conversion rules:

Inferred type of an FFI Result (BT-4023): because the boundary always wraps the error reason, the spec reader types the error side as an Exception, never as the spec's reason type. {ok, T} | {error, R} and ok | {error, R} infer Result(T, Exception) and Result(Nil, Exception) whatever R is (an atom, a posix() enumeration, term()). The one refinement is a #beamtalk_error{} reason, which always wraps to an Error subclass and so infers Result(T, Error). The rule lives in one place, beamtalk_spec_reader:format_result_type/2.

Lone ok/error return specs (ADR 0121, type inference): A non-union Erlang return spec of -> ok. or -> error. — including annotated forms like -> Result :: ok. — is now recognized as Result(Nil, Exception) or Result(Dynamic, Exception) respectively, matching the runtime coercion that coerce_result/1 already applies. Previously these lone atoms fell through to Symbol in the type inference, creating a static/dynamic type mismatch.

Opting out of Result conversion (BT-3836): Result conversion is unconditional for FFI returns, which is wrong for a Beamtalk-owned module whose functions return user data (Ets hands back whatever value was stored, so a stored #ok must stay #ok). Such a module exports beamtalk_ffi_raw_results/0 returning true, and beamtalk_erlang_proxy then passes its results through unchanged. Only opt out when none of the module's functions signal success or failure with ok / {ok, _} / {error, _} returns, since the opt-out removes the conversion for those too. The opt-out is runtime-only: the spec reader (ADR 0121) still infers Result for an -> ok or ok | error spec, so an opted-out module must not give its exported functions such return specs, or the inferred type and the runtime value will disagree.

Atom-enum precedence (type inference): When the spec reader maps a pure-atom union type containing atoms beyond ok/error, it infers a singleton union rather than applying ADR-0076 Result recognition. Unions whose atoms are a subset of {ok, error} and lone ok/error atoms infer as Result. For example, a spec of text | json | xml infers #text | #json | #xml, while ok | error or a bare ok infers Result.

⚠️ Type/runtime mismatch for enums containing ok/error. Type inference and runtime coercion use different rules. A spec like ok | error | pending infers the singleton union #ok | #error | #pending at the type level, but runtime ok/error coercion (coerce_result/1) is unconditional and spec-unaware: at runtime a bare ok still arrives as Result ok: nil and a bare error as Result error: nil. So code that matches the inferred #ok/#error singletons passes the type checker but never matches at runtime for those branches. When a spec uses ok or error as semantic enum members, handle those call-site branches as Result, not as the inferred singleton (only the non-ok/error members — here #pending — arrive as singletons).

undefined stays #undefined: Erlang undefined in an FFI return type spec maps to the singleton #undefined (a Symbol), not Nil. The FFI boundary does not coerce undefined → nil — callsites that want nil semantics must convert explicitly.

Scope: Conversion applies only to FFI calls via Erlang module method: args. Messages received from Erlang processes via receive or actor mailboxes remain raw Tuples. Use Result fromTuple: to explicitly convert those:

// Converting a Tuple received from a message
tuple := receiveMessage  // raw {ok, data} Tuple from Erlang process
result := Result fromTuple: tuple
result value  // => data

Migration from Tuple-based FFI code:

// Before (Tuple-based, pre-ADR-0076 — FFI returned raw Tuples):
result := Erlang file read_file: path
result isOk ifTrue: [result unwrap] ifFalse: ["error"]  // Tuple methods

// After (Result-based):
result := Erlang file read_file: path
result ifOk: [:content | content] ifError: [:e | "error"]
// Or simply:
result value  // raises on error

Error handling — wrap by default (ADR 0101): every FFI call is safe by default. The boundary treats the two channels a BEAM function can use independently, and they are mutually exclusive per call (a function either returns or raises):

Outcome of the callChannelBeamtalk resultHandle with
returns {ok, V} / {error, R}return valuea Result(V, R) valueisOk / value / andThen:
raises error:Reason (badarg, {badkey,_}, function_clause, …)exceptiona raised #beamtalk_error{}on:do: / ensure:, or bubbles to the REPL
raises exit:Reasonexceptionpropagates unwrapped (an enclosing on:do: catches it as erlang_exit)supervision / let-it-crash
raises throw:Termexceptionpasses through unchanged^ / Beamtalk exceptions

The guarantee: a user never sees a raw Erlang error tuple. A badarg becomes a structured #beamtalk_error{} (kind type_error) with a hint, not a bare {badarg, [...]} — most visible at the REPL, where the abstraction is most exposed. exit:/throw: are deliberately not wrapped, so (Erlang erlang) exit: #killed still terminates the process with reason killed.

Same function, both channels. Because the channels are orthogonal, one function can use both: File readAll: returns a Result error: for the modeled missing-file case, but raises a #beamtalk_error{} if called with a non-String path. The rule is Result for expected/recoverable outcomes the API models, exceptions for misuse/faults. Wrapping changes no return type — a raised #beamtalk_error{} is invisible to the type system, so Result stays the only type-visible error channel.

A raised FFI error is catchable as BEAMError, ExitError, or ThrowError. The handler block parameter is typed from the exception class argument, so e in on: BEAMError do: [:e | ...] is inferred as BEAMError (not Dynamic):

[Erlang erlang error: #badarg] on: BEAMError do: [:e | e message]
// => "badarg"
// e is typed as BEAMError — `e message` type-checks without warnings

The raw error term (Exception>>reason, BT-3954). message is a rendered string. To match on the underlying Erlang term, ask for reason. It returns the R of an FFI {error, R} (the exception that Result error: wraps) or the reason of a raw error:/exit:/throw: caught via on:do:, as an atom or tuple. FFI values pass through the usual boundary coercions first, so a charlist reason arrives as a String. When no underlying term was recorded, as for Error signal: and self error:, reason returns nil. Stdlib natives follow the same rule (BT-3970, BT-4236): a failure that comes from Erlang/OTP keeps its term after it is classified into a kind, so (File readAll: "missing.txt") error is a #file_not_found whose reason is #enoent, a failed Json parse: keeps the parser's term (e.g. #unexpected_end), and an invalid Regex from: pattern keeps re:compile's {ErrCharlist, Position}, the same term Erlang re compile: answers (element 1 is OTP's charlist, a List, not a String). The one non-OTP case is Result unwrap on a plain error value, whose reason is that value. Only a Result error: produced at the FFI boundary holds an Exception. A Result error: #sym built in Beamtalk holds the value itself, so read it with error, not error reason:

(Erlang string to_integer: "abc") ifError: [:e | e reason]
// => #no_integer
[Erlang erlang error: #econnreset] on: Exception do: [:e | e reason]
// => #econnreset
[#(1, "x") sum] on: TypeError do: [:e | e reason]
// => #badarith  (classified as type_error, original term still available)
[Error signal: "boom"] on: Error do: [:e | e reason]
// => nil
(File readAll: "missing.txt") error reason
// => #enoent  (classified as file_not_found, posix term still available)

Carrying a reason: signal:reason: (BT-4159). Beamtalk exceptions have no instance fields, so to attach machine-readable data when signalling, use the class-side signal: message reason: term. The term can be any value; reason answers it in on:do: (type Object | Nil, so narrow with isKindOf: or match), it survives propagation across processes, and uncaught reports print it as a Reason: line. There is no separate error:reason:; Error signal: msg reason: term is the equivalent.

[Error signal: "closed" reason: #econnreset] on: Error do: [:e | e reason]
// => #econnreset

Structured details (Exception>>details, BT-4174). Natives that know more than the message says record it as structured details: details answers a Dictionary keyed by Symbol (empty when nothing was recorded), so read the value with at: instead of parsing the English message. For example, Binary asString on invalid UTF-8 answers Result error: holding a parse_error whose #offset is the byte offset of the first invalid sequence. A nested Beamtalk error stored in the details answers as an Exception and an absent (Erlang undefined) value as nil. Other values are the recorded terms as-is, without the FFI boundary coercions reason gets. Natives record text details (a File error's #path, rename:to:'s #from/#to) as Strings, so (File readAll: "missing.txt") error details at: #path equals "missing.txt" (BT-4229).

(Binary fromBytes: #(104, 101, 255)) asString error details at: #offset
// => 2
[Error signal: "boom"] on: Error do: [:e | e details]
// => #{}

Re-raising unchanged: pass vs signal (BT-4057). e signal on a caught exception raises a fresh error with a new stacktrace, so a caught ExitError or ThrowError comes back out as an error. e pass re-raises with the original Erlang class (error, exit or throw), reason and call sites, so an outer handler (or the process) sees the original failure: exit: #normal still ends the process normally. It re-raises the stacktrace captured when the exception was caught, with each frame's argument values reduced to its arity, as e stackTrace shows them. On an exception that was never caught (Exception new pass), pass behaves like signal.

Where a class-side signal raises (BT-4115, BT-4270). Error signal: m, MyError signal, Error signal: m reason: r and Exception signalKind:class:selector:hint: sent to a class literal raise in the calling process: when the compiler sees that the class method resolves to one of Exception's class-side signal primitives, which need nothing from the class but its name, the call site raises through the primitive directly instead of going through the class's process. The exception is the same as a dynamic send (cls signal: m) raises. The shortcut is checked at run time, with the same static call key as other static class sends (ADR 0142 §2, BT-4316): it is taken only while the send still resolves to Exception's compiled primitive. A class signal: override (in a subclass, or added later by hot reload) or a runtime class-method fun that replaces it takes the ordinary class send instead, so the override runs, also from call sites compiled before it. An override on an ancestor of the receiving class counts as that ancestor's method, so it takes the ordinary class send too, and runs with the receiving class as self (BT-4307). e stackTrace builds its StackFrame objects each time it is read, not when the exception is caught, so class names are resolved at read time.

[(Erlang erlang) exit: #shutdown] on: Exception do: [:e | e pass]  // exits with #shutdown

In an actor's ! cast, handleInfo: or continueWith: step, an exit with reason #normal or #shutdown stops the actor with that raw reason (so onExit: receives #normal, not an {Exception, Stacktrace} tuple); every other failure crashes with {Exception, Stacktrace} as described in ADR 0134. {shutdown, Term} is deliberately excluded and still crashes the actor. Known limitation: hand-written Erlang (runtime-path) actors still normalise every failure to an error.

For an FFI Result r, r error is an Exception (the type checker infers Result(T, Exception), see "Inferred type of an FFI Result" above) and r error reason is the raw Erlang term. Comparing the Exception itself to a Symbol, as in r error =:= #closed, is always false, so the compiler warns: comparing an Exception to a Symbol with `=:=` is always false; use `r error reason` , with the hint did you mean `r error reason =:= #closed`?. The warning covers =:=, ==, =/= and /= (the negated forms are always true) in either operand order, for any Exception-typed expression compared with a Symbol literal. For an Error-typed value the hint also suggests kind, since a structured Beamtalk error usually records no raw reason. Silence a deliberate comparison with @expect type.

A native: method's wrapped error carries the Beamtalk Class/selector (e.g. Type error in 'take:' on Stream), whereas inline (Erlang …) FFI carries the Erlang-facing ErlangModule context (e.g. Type error in 'atom_to_list' on ErlangModule) — a documented limitation, since the proxy knows the MFA but not the calling class.

Type Specs for Native Modules

When writing native Erlang modules that implement Beamtalk class methods, prefer the exported Dialyzer-facing types for Result and wrapped error values instead of bare map(). These types are primarily useful for Erlang -spec annotations and Dialyzer; Beamtalk's spec importer may resolve them to Dictionary in generated Beamtalk signatures rather than Result(...) / Exception.

TypeDescription
beamtalk_result:t()Any Result (unparameterized)
beamtalk_result:t(OkType, ErrType)Result with known ok/error types
beamtalk_error:t()Exception tagged map (the wrapped error visible to Beamtalk)

Example specs:

-module(beamtalk_mylib).
-include_lib("beamtalk_runtime/include/beamtalk.hrl").

%% Unparameterized — any Result
-spec 'readConfig:'(binary()) -> beamtalk_result:t().
'readConfig:'(Path) ->
    case file:read_file(Path) of
        {ok, Bin} ->
            beamtalk_result:from_tagged_tuple({ok, Bin});
        {error, Reason} ->
            Err0 = beamtalk_error:new(io_error, 'MyLib', 'readConfig:'),
            Err1 = beamtalk_error:with_details(Err0, #{path => Path, reason => Reason}),
            beamtalk_result:from_tagged_tuple({error, Err1})
    end.

%% Parameterized — precise ok/error types for Dialyzer
-spec 'parse:'(binary()) -> beamtalk_result:t(map(), beamtalk_error:t()).
'parse:'(Data) -> ...

These types are defined in:

FFI Collection Element Types

The spec importer carries collection element types from Erlang -spec attributes (ADR 0075 amendment), so iterating an FFI-typed list binds block parameters to the element type instead of Dynamic:

Erlang specImported Beamtalk type
[integer()]List(Integer)
[{atom(), pos_integer(), atom()}]List(Tuple(Symbol, Integer, Symbol))
{atom(), binary()}Tuple(Symbol, String | Binary)
[term()] / tuple()List / Tuple (uninformative elements collapse to the bare type)
// allSendsIn/1 is specced [{atom(), pos_integer(), atom()}]:
sends := (Erlang beamtalk_interface) allSendsIn: source
sends do: [:s |
  // s is Tuple(Symbol, Integer, Symbol) — no annotation needed
  selector := s at: 1   // inferred Symbol
  arity := s at: 2       // inferred Integer
]

Literal-index tuple access: Sending at: with a literal integer index to a value of a known Tuple(T1, …, Tn) type infers the element type at that 1-based index:

pair := someTupleTyped     // Tuple(Symbol, Integer)
pair at: 1                  // inferred Symbol
pair at: 2                  // inferred Integer

A non-literal index (pair at: i) or an out-of-range literal falls back to Dynamic — no false-positive warning. An untyped tuple() spec (unknown arity) stays bare Tuple, so at: on it remains Dynamic as before.

Number Literals

Integers and floats have three spellings beyond plain decimal digits. All of them are ordinary Integer and Float values at run time; the spelling only matters in source.

Radix integers are written <radix>r<digits>: the radix is a decimal number from 2 to 36, and the digits are 0-9 and A-Z (upper or lower case) for that radix. A - written directly in front is part of the literal.

16rFF       // => 255
2r1010      // => 10
36rZZ       // => 1295
-16rFF      // => -255
16rFF + 1   // => 256

Radix integers have no practical size limit, like decimal ones (16rFFFFFFFFFFFFFFFFFF is 4722366482869645213695, a BEAM bignum); a literal over 10,000 characters is rejected. A radix outside 2-36 (37r1), a digit that is not valid in the radix (16rG) and a missing digit (16r) are compile errors.

Exponent floats are a decimal number, an e or E, an optional + or -, and at least one digit. A literal with an exponent is always a Float, even with no decimal point:

2.5e3 == 2500.0 // => true
1e-3 == 0.001   // => true
1e3 == 1000.0   // => true
1e3 class       // => Float

A float prints in the shortest form that reads back as the same number, and which form that is depends on the value: 1e2 prints 100.0, while 1e3 and 1000.0 both print 1.0e3.

An exponent with no digits (1e) is a compile error, and so is a literal that overflows a 64-bit float (1e309: "Float literal out of range").

beamtalk fmt keeps the spelling you wrote (16rFF stays 16rFF, 1e-3 stays 1e-3).

List Cons Literal

#(head | tail) builds a list by prepending to an existing list, the expression form of Erlang's [H | T]. Several heads may come before the |, and the tail is any unary expression (parenthesise a binary or keyword send). The tail list is not changed:

tail := #(1, 2, 3)
#(0 | tail)        // => #(0, 1, 2, 3)
#(1, 2 | #(3, 4))  // => #(1, 2, 3, 4)
#(1 | #())         // => #(1)

The same form is a pattern, in a match: arm and on the left of :=: see List Patterns.

Tuple Literals (ADR 0136)

{e1, e2, ...} builds a raw Erlang tuple (class Tuple). It is the expression form of the {a, b} tuple pattern, and the value is exactly the Erlang term: symbols and true/false/nil are atoms, so {#active, false} is Erlang's {active, false}. This makes FFI option lists read like the Erlang docs:

(Erlang gen_tcp) listen: port with: #(#binary, {#active, false}, {#reuseaddr, true}, {#backlog, 1024})

pair := {#backlog, opts at: #backlog}   // elements are keyword-level expressions
{#ok, 1} =:= (Tuple withAll: #(#ok, 1)) // => true
{#a, 1} at: 2                           // => 1 (inferred Integer)
single := {#ok}                          // 1-tuple
empty := {}                              // 0-tuple
opts := #({#local, path}, {#nodelay, true},)  // trailing comma is allowed

FFI Type Stub Files (ADR 0075 Phase 2)

When the auto-extracted Erlang -spec types are missing or imprecise for a module, you can provide hand-written type stubs in a project's stubs/ directory. Each .bt file there uses declare native: to declare type signatures for Erlang module functions:

/// Type declarations for Erlang module `lists`.
declare native: lists
  reverse: list :: List(T) -> List(T)
  seq: from :: Integer to: to :: Integer -> List(Integer)
  member: elem :: T in: list :: List(T) -> Boolean

Stub signatures use the same syntax as Protocol method signatures — parameter names with optional :: Type annotations and an optional -> ReturnType — but never have a => body. Unary functions use a bare name:

declare native: erlang
  node -> Symbol
  self -> Pid

declare is a contextual keyword — it remains a legal identifier everywhere else.

Build integration: beamtalk build and beamtalk lint automatically scan the project's stubs/ directory (no beamtalk.toml config needed). Stub declarations merge into the FFI type registry at function/arity granularity: a stub for lists:reverse/1 overrides only that entry; lists:nth/2, not declared in the stub, still uses the auto-extracted type from the .beam file.

Version-drift detection: A stub function/arity that doesn't exist in the corresponding .beam module's real exports produces a warning anchored to the stub file, so stubs stay in sync with the Erlang modules they describe.

Restrictions:

Generating stubs: Use beamtalk generate stubs to bootstrap stub files from .beam abstract code:

beamtalk generate stubs lists maps string
# Output: stubs/lists.bt, stubs/maps.bt, stubs/string.bt

Loading Code into the Workspace

Beamtalk source files are loaded into the live workspace via the Workspace class-side facade (there is no :load REPL command). Loaded classes are immediately available — existing actors pick up new code on next dispatch.

// Load one file (works from compiled code and MCP too)
Workspace load: "examples/counter.bt"
// => #(Counter)

// Recompile every changed file of the project (needs beamtalk.toml);
// the REPL shortcut is `:sync`
Workspace sync

// Reload a specific class from its source file
Counter reload
// => Counter  (recompiled and hot-swapped)

Workspace load: takes a single file; a directory raises an error. Use Workspace sync to load a whole project.

See Workspace and Reflection API for the full Workspace facade interface.


Gradual Typing (ADR 0025)

Beamtalk supports optional type annotations and typed classes. Type checks are compile-time warnings (not hard errors), so interactive workflows remain fast.

Typed Class Syntax

typed Actor subclass: TypedAccount
  state: balance :: Integer = 0
  state: owner :: String = ""

  deposit: amount :: Integer -> Integer =>
    self.balance := self.balance + amount
    self.balance

  balance -> Integer => self.balance

late Slots (ADR 0124)

A nilable slot is not automatically a late candidate. The question late answers is narrow: is this slot acquired exactly once, by an explicit lifecycle call, and correct for as long as it stays assigned — never whether its type merely permits nil. Most nilable slots in real Beamtalk code use nil to mean something else, and converting them to late would be wrong. Exdura's timer manager resolves its dependencies by name on every read, deliberately, so that a supervisor restart of either dependency is picked up automatically instead of leaving a stale reference behind:

typed Actor subclass: TimerManager
  // (ADR 0079) instead of passing live refs, since neither exists yet
  // when the child spec is built. `engine`/`eventStore` resolve fresh by
  // name in that case, so a `rest_for_one` restart of either is picked up
  // automatically instead of leaving a nil/stale field.
  state: engine :: WorkflowEngine | Nil = nil
  state: eventStore :: EventStore | Nil = nil

An ordinary method (currentEngine/currentEventStore, on the sibling ExduraClient) does the by-name lookup on every call. If engine were converted to late state: engine :: WorkflowEngine and assigned once from a resolved reference, a later restart of WorkflowEngine would leave the stale pid behind, unnoticed — exactly the failure this slot exists to avoid, and exactly what late cannot express: a late slot is absent-or-assigned, never "assigned, but now to the wrong thing." So the distinguishing question is never "can this hold nil?" — it is "would a stale, already-assigned value here be wrong?" If yes, the slot stays nilable and keeps resolving fresh in an ordinary method, the way currentEngine does — that method stays a method, not a slot kind; late has no "recompute on every read" mode and does not try to. Convert only a slot in the other shape: acquired exactly once by an explicit lifecycle call (open a subprocess, start a listener, attach a resource) and correct for the rest of that resource's life — Symphony's CodexClient proc below.

late is a declaration-level modifier on state: for a slot in that second shape — legitimately unassigned after initialize, acquired later by an explicit lifecycle call — instead of being declared nilable and nil-checked at every read:

typed Actor subclass: CodexClient
  late state: proc :: Subprocess   // not `proc :: Subprocess | Nil = nil`
  state: workspacePath :: String

  launch -> Nil =>
    self.proc := Subprocess open: "/bin/bash" args: #() dir: self.workspacePath

The modifier precedes the declaration keyword, matching the class-header modifier position (sealed typed Actor subclass: …). It requires a type annotation, and that type must not admit Nil and must have no default value — a late slot has exactly two states, absent and assigned, and its declared type is always non-nilable. Five compile-time Errors govern where late may appear:

  1. late field: on a Value — a Value is fully constructed and never reassigned (below).
  2. late state: with no type annotation — the point of late is a non-nilable declared type, and an untyped slot already defaults to nil with no check.
  3. late state: on a type that admits nil — a syntactic T | Nil, but also Object and ProtoObject (nil is an instance of both), Dynamic (which accepts every value unchecked), and any alias or protocol that admits nil. A slot whose type already admits nil is never in the state late describes.
  4. late state: with a default value — a slot with a default is never unset.
  5. late state: on a native: Actor, or late state:/field: on Object — already errors before late is even considered (ADR 0056 forbids state: on a native: Actor; ADR 0067 gives Object no instance data at all), and late does not change that.
late state: x            // error (2): requires a type annotation
late state: x :: T | Nil // error (3): drop `late` or narrow the type to exclude nil
late state: x :: Object  // error (3): `nil` is an `Object`, so the type admits nil
late state: x :: T = v   // error (4): a slot with a default is never unset

late is rejected on a Value's field: (error 1) — a Value is fully constructed by new/new:/its keyword constructor and never reassigned, so "assigned later" has no meaning; make the field optional (| Nil = nil) or hold the resource in an Actor instead. Outside declaration position late stays an ordinary identifier (late := 1) or method name.

Slot kinds and fieldKinds/allFieldKinds. Every declared slot has a kind — #eager (the default, no modifier) or #late — reflectable via Behaviour>>fieldKinds (this class's own slots only) and allFieldKinds (this class's plus every inherited slot, the flattened chain, mirroring fieldNames/allFieldNames):

CodexClient fieldKinds
// => #{#proc => #late, #workspacePath => #eager}

This draws the identical instance-vs-declared line fieldNames/ allFieldNames already draw (ADR 0035): Cls fieldKinds/ Cls allFieldKinds answer the declared schema — a late slot is always listed there, assigned or not — while an instance's fieldNames answers the keys actually present in its state map, so an unassigned late slot is not listed there. That is why c fieldNames silently omitting #proc and c hasField: #proc answering false read as the same fact seen from two angles, not a contradiction: one reports declared shape, the other reports assignment.

A late slot is excluded from the post-initialize definite-assignment check. Reading it before assignment raises UninitializedStateError — and "before assignment" means exactly that its key is absent from the state map. Presence — not value — is assignment: if an open-world writer (spawnWith: with a non-literal map, fieldAt:put:, perform:) has planted a nil there without going through ordinary self.slot := assignment, the key is present and the read answers nil, exactly as hasField: reports it assigned (BT-4061). late does not make a non-nilable declared type sound against those writers; it makes the direct read and hasField: agree on what "assigned" means. self.slot (or fieldAt: #slot) is the raising direct read; hasField: #slot is the non-raising presence test to ask first — Object's hasField:/ clearField: (ADR 0035's field-prefixed reflection family) make a late slot usable, not just declarable: hasField: answers whether it is currently assigned, and clearField: returns it to unassigned so it can be acquired again (maps:remove, not a sentinel value):

typed Actor subclass: CodexClient
  late state: proc :: Subprocess
  state: workspacePath :: String

  launch -> Nil =>
    self.proc := Subprocess open: "/bin/bash" args: #() dir: self.workspacePath

  stopProcess -> Nil =>
    (self hasField: #proc)
      ifTrue: [self clearField: #proc]
    nil

hasField: and clearField: are declared on Object, so they answer for every receiver, not only late-slot actors: hasField: on a Value answers whether the named field is declared, and on a primitive (Integer, String, …) always answers false — never raises. clearField: on a Value is the same "Cannot modify slot on value type" error fieldAt:put: already raises, since a Value is fully constructed and never reassigned. A class has no slots (ADR 0153), so none of these reflection sends reach a class: SomeClass fieldAt: #x, fieldAt:put:, hasField: and clearField: raise does_not_understand, as does self fieldAt: #x inside a class method. Read a class's constant with its class method (SomeClass x). A class that defines a class method of one of those names answers it on every route.

Supplying a late slot via spawnWith: counts as assigned — this is legitimate dependency injection (substituting a value for a slot normally acquired by a lifecycle call), not a violation of "absent until assigned": see the spawnWith:-injection clause beside the spawnWith: key-checking rule in Actor Message Passing below. Converting a slot between eager and late (or back) is a shape change and bumps shapeVersion: — see Chain and reconcile semantics for the reconcile-table row and the reload-time tooling finding that flags a flip landing without a version bump.

Unguarded late-slot reads in lifecycle hooks. A direct self.slot read of a late slot inside terminate: or handleInfo: (or one level of self-send from either) that isn't guarded by (self hasField: #slot) ifTrue: [...] produces a compile-time warning (unguarded-late-read diagnostic category). In terminate: a raised error is swallowed (terminate/2's dispatch is try-wrapped), so an UninitializedStateError from an unguarded read there never surfaces and the cleanup is silently skipped. In handleInfo: the error crashes the server (ADR 0134), so an unguarded read turns an ordinary message into a crash and restart. The fix is the hasField: guard shown above, not a suppression — like definite-assignment, there is no site-level @expect category for this diagnostic. Per-project severity is configurable via the [diagnostics] table (unguarded-late-read key — see the Package Management guide).

Definite Assignment (ADR 0124)

The compiler checks, at a class's construction site, that every declared, typed, non-nilable, no-default, non-late slot is guaranteed a real value — the same predicate ADR 0078's runtime backstop already used for Actors, now also checked statically, and now for Values too.

The predicate. A state:/field: slot requires definite assignment when it carries a type annotation, has no default value, its declared type does not admit Nil (resolving aliases and intersection/negation operators), and it is not declared late:

state: count :: Integer            // requires assignment
state: label :: String | Nil       // no — Nil is a valid value
state: count :: Integer = 0        // no — has a default
state: count                       // no — untyped, defaults to nil
late state: proc :: Subprocess     // no — declared assigned later (see above)

Where it reports: the construction site, not the declaration. A declaration alone is not enough evidence — the slot might be supplied at every real call site — so the diagnostic fires on Cls spawn / Cls new, or a literal-map Cls spawnWith: #{...} / Cls new: #{...} that omits the slot; only a literal map is inspected, the same boundary the spawnWith: key-checking rule above uses:

typed Actor subclass: Connection
  state: socket :: Socket
  state: retries :: Integer = 0

Connection spawn
//         ^ warning: `Connection` declares `socket :: Socket` with no
//           default, and no `initialize` in its chain assigns it.
//           `Connection spawn` supplies no `socket`, so it may raise
//           `UninitializedStateError`

The four fixes, named in the diagnostic's hint: supply the slot at the construction site, give it a default value, widen its type to admit Nil, or declare it late (Actors only, since late field: is rejected on a Value — see above).

The Actor/Value asymmetry. For an Actor subclass:, this diagnostic is an early warning in front of ADR 0078's existing runtime check — a spawn it flags was already going to raise UninitializedStateError, just later, at spawn time instead of at compile time. For a Value subclass:, it is the only check there is — Values have no initialize and no post-construction runtime validation, so StoredSnapshot new on a typed-no-default field silently yields an instance holding nil behind a declared non-nilable type, with nothing to catch it at runtime. That makes the default Warning severity a real gap, not merely an advisory one, for a Value-heavy codebase — see escalation below.

The deserialization limit. A Value built by deserialization has no construction site at all:

typed Value subclass: StoredSnapshot
  field: state :: ReplaySnapshot   // typed, no default

  class fromBinary: content :: Binary -> StoredSnapshot =>
    result :: StoredSnapshot := Binary deserialize: content
    result

Binary deserialize: is not new/new:, so the check never inspects this site — the local type annotation on result is an assertion at a type-erasure boundary, not something the checker can verify, and nothing is reported here (consistent with the open-world silence of ADR 0100 where knowledge is absent). A class in this position should default the field or widen it to | Nil.

Severity and @expect. The diagnostic is Warning when the checker's knowledge is complete — the ancestor chain is fully known, no ancestor is native:, and (for Actors) no fieldAt:put:/perform: write anywhere in the class is invisible to the must-analysis — and Hint otherwise. There is no dedicated @expect category for this diagnostic, by design: late is the language construct that opts a slot out, not an annotation that silences a warning about it. A test that deliberately constructs an instance with the slot left unassigned suppresses the diagnostic with @expect all.

Escalating to Error. Per-project severity is ADR 0100 Rule 3's [diagnostics] table (definite-assignment = "error" in beamtalk.toml — see the Package Management guide). Because a Value's Warning has no runtime backstop, a Value-heavy codebase has more reason to make that escalation than an Actor-heavy one — provided the bare-new-override check is in place: a class that defines its own class new/new: already exempts that construction site, the same as any other override of the auto-generated constructor.

Annotation Forms

// Unary return annotation
getBalance -> Integer => self.balance

// Keyword parameter annotation
deposit: amount :: Integer => self.balance := self.balance + amount

// Binary parameter + return annotation
+ other :: Number -> Number => other

// Multiple keyword parameters with annotations
sum: left :: Integer with: right :: Integer -> Integer => left + right

// Union type annotations parse (full checking is phased in)
maybeName: flag :: Boolean -> Integer | String =>
  ^flag ifTrue: [1] ifFalse: ["none"]

// Self return type — resolves to the static receiver class at call sites
// (only valid in return position, not parameters)
collect: block :: Block(E, R) -> Self =>
  self species withAll: (self inject: #() into: [:acc :each |
    acc addFirst: (block value: each)
  ]) reversed

// At call sites, Self resolves to the static receiver type:
// (List new collect: [:each | each])  — inferred return type: List
// (Set new collect: [:each | each])   — inferred return type: Set

// Self also substitutes inside nested generic return types
class named: name :: Symbol -> Result(Self, Error) => ...
// (Counter named: #c) — inferred return type: Result(Counter, Error)

// On parameterised receivers, Self preserves type arguments:
// (Box(Integer) new) someMethod — where someMethod -> Result(Self, Error)
//   inferred return type: Result(Box(Integer), Error)

// Self class — the receiver's metatype, i.e. the class object (ADR 0083).
class -> Self class => @primitive "class"
// (Counter new) class — inferred type: the metatype-of-Counter (rendered
// `Counter class`). Sends are routed class-side: `(Counter new) class new`
// infers a Counter instance, and `(Counter new) class instanceCount`
// type-checks against Counter's class-side methods.

// <ClassName> class — a named class metatype annotation.
// Valid in any type position (fields, parameters, return types, locals).
// Resolves to the metatype-of-<ClassName> (a tracked type, ADR 0083), so
// class-side methods on that class resolve without false DNU warnings, and a
// class value flows with type through variables, collections, and FFI returns.
// The metatype is name-only — the class object is unparameterized (ADR 0068),
// so there is no `List(E) class`, only `List class`. Type-erased at runtime.
field: actorClass :: Actor class | nil = nil
// After `actorClass isNil ifTrue: [^nil]`, actorClass is narrowed to
// `Actor class` — class-side methods like `isSupervisor` type-check.

// Class literal inference: a bare class literal (`Counter`) infers as the
// metatype `Counter class`, so class values stored in variables, collections,
// or returned from FFI calls route class-side sends correctly without annotation.
klass := Counter            // inferred Counter class (the metatype)
klass new                   // inferred Counter (an instance)
klass instanceCount         // resolves class-side method

// Metatype subtyping: `C class <: Class <: Behaviour <: Object`, so a class
// value satisfies `:: Class` / `:: Behaviour` parameters and `List(Behaviour)`
// FFI returns. `new` / `basicNew` on a *concrete* class metatype infers an
// instance of that class; on an *abstract* class (e.g. `Collection`,
// `Behaviour`) it stays Dynamic — instantiating an abstract class is an error.

// <Protocol> class — a protocol metatype annotation (ADR 0144). For a
// protocol `P`, `P class` is the class object of *any* class conforming to
// `P`: `C class <: P class` iff `C conformsTo: P` (the same structural check,
// open-world rules included). Sends resolve against `P`'s `class`
// requirements (typed from their declared signatures), then the class-object
// protocol every class answers (`name`, `printString`, `respondsTo:`, …).
// `new` / `basicNew` infer `P` unless `P` declares `class new`. A value that
// *is* a protocol object is typed `:: Protocol`. See Class Method Requirements.
field: transport :: Transport class = TCPTransport
// `self.transport send: s data: d` is checked against `Transport`'s
// `class send:data:` requirement and typed `Result(Nil, Object)`.

// Block parameter annotations — accepted by the parser and preserved by
// `beamtalk fmt`. A union (or `&`/`\` chain) needs grouping parens so its
// `|` doesn't swallow the block's own `|` parameter separator.
#(1, 2, 3) collect: [:x :: Integer | x + 1]
self run: [:x :: (Integer | String) | x]

Current Semantics

Local Variable Type Annotations

Local variables can carry a type annotation using name :: Type := expr. The declared type overrides the inferred type of the right-hand side, which is useful at type-erasure boundaries (FFI returns, deserialization, untyped APIs). The annotation is erased at codegen — there is no runtime effect.

x :: Integer := 42
dict :: Dictionary := Binary deserialize: content
name :: String | nil := dictionary at: "name"
r :: Result(Integer, Error) := computeSomething

Supported type forms: simple (Integer), parametric (Result(T, E)), and union (String | nil).

Type checking: The compiler warns when the RHS type is unrelated to the declared type (e.g., x :: Integer := "hello"). Narrowing assertions — where the declared type is more specific than the inferred type, or the right-hand side is Dynamic or Object — are accepted (BT-2015), but nothing checks them at runtime: n :: Integer := opts at: #max is an unchecked cast, and if the claim is wrong the failure shows up later and somewhere else. They are visible in two places (BT-4719):

Redundant annotations (ex :: Exchange := self exchange, the "Redundant type annotation" lint) and widening annotations (status :: Integer | Nil := nil) are not narrowing casts and behave as before. Dynamic and Never RHS types are always accepted. Checked casts are a separate design question (BT-4772).

Dynamic Type Visibility (ADR 0077)

When the compiler cannot determine an expression's type, it infers Dynamic. Beamtalk makes Dynamic visible so you can see exactly where the compiler lacks type information and why.

Dynamic with Reasons

Each Dynamic type carries a reason explaining why the type could not be determined:

ReasonDescriptionWhat to fix
unannotated parameterParameter has no type annotationAdd :: Type to the parameter
unannotated returnMethod has no return type and body could not be inferredAdd -> Type return annotation
dynamic receiverReceiver is Dynamic, so message send result is DynamicFix the receiver's type first
ambiguous control flowControl flow produces incompatible typesAdd type annotations to branches
untyped FFIErlang FFI call with no spec or all-Dynamic specAdd -spec to the Erlang module
unresolved selectorThe receiver's class is known but no visible method answers the selector, and the checker cannot enumerate the class's whole method surface (a doesNotUnderstand:args: override, or an ancestor it cannot see). When it can prove the method is absent it reports does-not-understand instead, and the result is not warned on againCheck the selector spelling; use @expect type if the class answers it dynamically
(none)Fallback — no specific reason availableShown as plain Dynamic

LSP Hover

When hovering over an expression in the editor, the LSP shows the inferred type including Dynamic with its reason:

Identifier: `handler` — Type: Dynamic (unannotated return)
Identifier: `result` — Type: Dynamic (dynamic receiver)
Identifier: `data` — Type: Dynamic (unannotated parameter)
Identifier: `count` — Type: Integer

When the reason is Unknown, the hover shows just Type: Dynamic. Previously, Dynamic expressions showed no type information at all — the type line was omitted entirely.

Typed Class Diagnostics

typed classes opt into thorough type checking. In addition to requiring parameter and return annotations on methods, typed classes produce warnings for:

Missing State Field Annotations

State fields without type annotations produce a warning:

typed Actor subclass: BankAccount
  state: balance = 0          // warning: Missing type annotation for state field
                               //          `balance` in typed class `BankAccount`
  state: owner :: String = ""  // OK — annotated

Dynamic Inference Warnings

When an expression in a typed class infers as Dynamic (for a root-cause reason like unannotated parameter or unannotated return), the compiler warns. Propagated reasons like dynamic receiver are not warned on separately since the root cause already has its own warning.

typed Actor subclass: BankAccount
  process: handler =>
    handler doWork    // warning: expression inferred as Dynamic in typed class
                      //          `BankAccount` (unannotated parameter)

Suppressing Type Warnings with @expect type

When Dynamic dispatch is intentional (e.g., a method that deliberately accepts any object), suppress the warning with @expect type on the preceding line:

typed Actor subclass: BankAccount
  process: handler =>
    @expect type
    handler doWork    // no warning — suppressed

@expect type suppresses all type-related warnings on the next expression, including type mismatches, does-not-understand hints, and Dynamic inference warnings. @expect all also works as a broader suppression.


Parametric Types — Generics (ADR 0068)

Beamtalk supports declaration-site parametric types (generics) with compile-time substitution. Type parameters use parenthesis syntax — Result(T, E) — keeping < reserved exclusively as a binary message (comparison operator). All generic type information is erased at runtime (zero cost).

Declaring a Generic Class

Classes declare type parameters in parentheses after the class name:

sealed Value subclass: Result(T, E)
  field: okValue :: T = nil
  field: errReason :: E = nil

  unwrap -> T =>
    self.isOk ifTrue: [
      self.okValue
    ] ifFalse: [(Erlang beamtalk_result) unwrapError: self.errReason]

  map: block :: Block(T, R) -> Result(R, E) =>
    self.isOk ifTrue: [Result ok: (block value: self.okValue)] ifFalse: [self]

  andThen: block :: Block(T, Result(R, E)) -> Result(R, E) =>
    self.isOk ifTrue: [block value: self.okValue] ifFalse: [self]

Type parameters are bare uppercase identifiers (by convention single letters: T, E, K, V, R). They appear in:

Using Generic Types

When using a generic class as a type annotation, concrete types replace the parameters:

// Annotating a variable
result :: Result(String, IOError) := File read: "config.json"
result unwrap    // Type checker knows: -> String

// Annotating a method parameter
processResult: r :: Result(Integer, Error) -> Integer =>
  r unwrap + 1   // r unwrap is Integer, Integer has '+'

// Annotating state
Actor subclass: Cache(K, V)
  state: store :: Dictionary(K, V) = Dictionary new

Type Inference Through Generics

The type checker performs positional substitution: when it encounters Result(String, IOError), it maps T -> String, E -> IOError, and substitutes through all method signatures:

r :: Result(Integer, Error) := computeSomething
r unwrap          // Return type T -> Integer
r map: [:v | v asString]   // Block param T -> Integer, return Result(String, Error)
r error           // Return type E -> Error

When concrete type parameters are unknown, they fall back to Dynamic:

r := someMethod        // someMethod returns bare Result (no type params)
r unwrap               // -> Dynamic (T is unknown)
r unwrap + 1           // No warning — Dynamic bypasses checking

Constructor Type Inference

For named constructors (ok:, error:, new), the compiler infers type parameters from the argument types:

r := Result ok: 42                  // Inferred: Result(Integer, Dynamic)
r unwrap                            // -> Integer

r2 := Result error: #file_not_found // Inferred: Result(Dynamic, Symbol)
r2 error                            // -> Symbol

Generic Inheritance

When a generic class extends another, the type parameter mapping must be explicit:

// Array passes its E to Collection's E
Collection(E) subclass: Array(E)

// IntArray fixes E to Integer
Collection(Integer) subclass: IntArray

// SortedArray passes E through
Array(E) subclass: SortedArray(E)

Block Type Parameters

Block(...) is special-cased — the last type parameter is always the return type:

Design Constraints

Dialyzer Spec Generation

Generic annotations generate expanded Dialyzer specs with concrete types at the BEAM interop boundary:

processResult: r :: Result(Integer, Error) -> Integer => r unwrap + 1

Generates:

-spec processResult(#{
  '__class__' := 'Elixir.Result',
  'okValue' := integer(),
  'errReason' := any()
}) -> integer().

Unresolved type parameters map to any() in Dialyzer specs.

Named type alias emission. When a module declares type aliases (ADR 0108), codegen emits matching named Erlang -type attributes into the compiled module. Method annotations referencing an alias name emit user_type references in their -spec attributes instead of any():

type Timeout = Integer | #infinity

Actor subclass: Worker
  run: t :: Timeout => // ...

Generates:

-type 'Timeout'() :: integer() | 'infinity'.
-spec run('Timeout'()) -> any().

(The bare ('Timeout'()) form omits the parameter name — both it and the named form (T :: 'Timeout'()) are valid Erlang specs; codegen emits the bare form, matching typical erlc output.)

Cross-package alias references (an annotation referencing an alias exported by a dependency) are not yet resolved in codegen — they still fall through to any().

REPL Type Display

The REPL displays generic type information when available:

> :help Result >> unwrap
unwrap -> T

When the workspace knows the concrete type parameters, :help substitutes them:

> r := Result ok: 42
> r unwrap
=> 42
// Type info: Integer (inferred from Result(Integer, Dynamic))

Structural Protocols (ADR 0068)

Protocols define named message sets. A class conforms to a protocol if it responds to all required messages — no implements: declaration needed. This is Smalltalk's duck-typing philosophy made explicit.

Defining a Protocol

Protocol define: Printable
  /// Return a human-readable string representation.
  asString -> String
  /// Return a developer-oriented representation (for debugging/REPL).
  printString -> String

Protocol define: Collection(E)
  /// The number of elements in this collection.
  size -> Integer

  /// Iterate over each element.
  do: block :: Block(E, Object)

  /// Transform each element, returning a new collection of the same kind.
  collect: block :: Block(E, Object) -> Self

  /// Return elements matching the predicate.
  select: block :: Block(E, Boolean) -> Self

Protocol bodies use class-body style — method signatures without => implementations. Doc comments are supported on each required method.

A protocol body may also carry provided methods — a signature with => and a body, flattened into every class that names the protocol in a uses: line. That is a trait, covered in full in § Traits below. The stdlib's own Comparable (stdlib/src/comparable.bt) is one: it requires only <, and provides >, <=, >=, between:and:, min:, max:.

Using Protocols as Types

Protocol names are used in type annotations the same way as class names — the compiler resolves the name and determines whether to perform nominal (class) or structural (protocol) checking:

// Structural/protocol type — Printable guarantees asString
display: thing :: Printable =>
  Transcript show: thing asString

// Generic protocol type
printAll: items :: Collection(Object) =>
  items do: [:each | Transcript show: each asString]

A protocol-typed value is still an object. A send to it resolves against the protocol's own selectors (required and provided, including those of protocols it extends) first, then against the methods every object answers (printString, respondsTo:, class, …), whose return types flow through — thing printString infers String. Any other selector is a does-not-understand (Printable does not understand 'frobnicate').

Automatic Conformance

Conformance is structural and automatic — no implements: declaration needed:

// String has asString -> conforms to Printable
// Integer has asString -> conforms to Printable
display: "hello"           // String conforms to Printable
display: 42                // Integer conforms to Printable
display: Counter spawn     // Counter conforms to Printable (inherited from Object)

Classes that override doesNotUnderstand: conform to every protocol (they can respond to any message).

Protocol Composition

// Require multiple protocols
sort: items :: Collection(Object) & Comparable => ...

// Protocol extending another
Protocol define: Sortable
  extending: Comparable
  /// The key used for sort ordering.
  sortKey -> Object

Class Method Requirements (BT-1611)

Protocols can require class-side methods using the class prefix, the same syntax as class definitions:

Protocol define: Serializable
  asString -> String
  class fromString: aString :: String -> Self

A class conforms to Serializable only if it has both the instance method asString and the class method fromString:. This is useful for factory methods, singleton patterns, and other class-level contracts.

Classes as strategies: P class (ADR 0144). To hold a class that implements a protocol's class-side contract — a class passed around as a strategy — type it P class. It denotes the class object of any class conforming to P:

C class <: P class      iff      C conformsTo: P
Protocol define: Transport
  class send: socket :: Object data: data :: Object -> Result(Nil, Object)
  class close: socket :: Object -> Result(Nil, Object)

Value subclass: Socket
  field: socket :: Object
  field: transport :: Transport class = TCPTransport   // any conforming class

  send: data :: Object -> Result(Nil, Object) =>
    result := self.transport send: self.socket data: data  // checked, typed
    result isOk ifTrue: [self countSent: data]               // `isOk` on Result
    result

Type Parameter Bounds

Type parameters can be bounded by protocols:

// T must conform to Printable
Actor subclass: Logger(T :: Printable)
  log: item :: T =>
    Transcript show: item asString    // Guaranteed by Printable bound

A type argument that does not conform to its bound warns (Type argument Integer for T in Boxed does not conform to Frob). The check runs at these annotation sites: field types, method parameter and return types, superclass type arguments, local annotations (b :: Boxed(Integer) := ...), and typed block parameters, in method bodies, nested blocks, match-arm bodies, state-field default expressions and top-level script statements. A typed pattern binding (b :: T) names a bare class (generic arguments there are a parse error), so it carries no type argument to check. A bound may name a protocol of the package, of a dependency, or a stdlib protocol (Comparable, Enumerable, JsonMappable, Printable, JsonRepresentable); a package's own protocol of the same name wins. A type argument the checker cannot see completely (Dynamic, a class with a doesNotUnderstand: override, a cross-file superclass) conforms. There is no separate construction site: type arguments appear only in annotations.

Runtime Protocol Queries

> Integer conformsTo: #Printable
=> true

> Integer conformsTo: #NonExistentProtocol
=> false

> Integer protocols
=> [#Printable, #Comparable]

> Protocol requiredMethods: #Printable
=> [#asString, #printString]

> Protocol conformingClasses: #Printable
=> [Integer, Float, String, Boolean, Symbol, Array, ...]

conformsTo: returns false for unknown or non-protocol names — a class cannot conform to something that is not a registered protocol.

Diagnostic Philosophy

Protocol conformance issues are warnings, never errors:

SituationSeverity
Protocol conformance unverifiableWarning
Missing method for protocolWarning
Namespace collision (class + protocol same name)Error (structural)

Traits (ADR 0127)

A trait is a Protocol define: body that carries at least one provided method — a signature with => and a body, alongside the protocol's ordinary required signatures (no =>). There is no separate Trait define: keyword; a trait is just a protocol with provisions, and it is used exactly like any other protocol.

// stdlib/src/comparable.bt
Protocol define: Comparable
  /// Required — the using class must implement this.
  < other :: Self -> Boolean

  // Provided — derived from `<`, flattened into every user.
  > other :: Self -> Boolean => other < self
  <= other :: Self -> Boolean => (other < self) not
  >= other :: Self -> Boolean => (self < other) not
  between: min :: Self and: max :: Self -> Boolean =>
    (self >= min) and: [self <= max]
  min: other :: Self -> Self => (self < other) ifTrue: [self] ifFalse: [other]
  max: other :: Self -> Self => (self < other) ifTrue: [other] ifFalse: [self]

A class receives a trait's provisions by naming it in a uses: line at the top of its body, immediately after the header and before any state:/ field: declaration or method:

sealed typed Value subclass: DateTime native: beamtalk_datetime
  uses: Comparable

  < other :: DateTime -> Boolean => self delegate
  // `>`, `<=`, `>=` stay hand-written (each its own FFI call) — DateTime's
  // own methods win over Comparable's provisions (see Precedence below).
  // Gained from Comparable: `between:and:`, `min:`, `max:`.

Self in a trait's signature is substituted with the using class at flattening time, so Comparable>>max: other :: Self -> Self becomes DateTime>>max: other :: DateTime -> DateTime on DateTime — exactly the signature a hand-written method would declare.

Composing more than one trait, and excluding:/overriding:

The full grammar of a uses: line:

uses: [package@]ProtocolName[(TypeArgs)] [excluding: #(#sel, …)] [overriding: #(#sel, …)]

A bare uses: ProtocolName resolves by first-definition-wins: the current file, then the rest of the package, then its dependencies, and last the stdlib's own traits (Comparable, Enumerable) — so any package can uses: Enumerable(E) without declaring a dependency, and a package's own same-named protocol takes precedence. A qualified uses: pkg@ProtocolName resolves only against that package's protocols, so two dependencies that each export a same-named protocol can be composed without ambiguity.

One trait per uses: line — several traits are several lines:

typed Actor subclass: WorkerPool
  uses: Enumerable(Worker)
  state: workers :: List(Worker) = #()

  elements -> List(Worker) => self.workers

excluding: drops one or more of a trait's provisions (Pharo's -), keeping the class's own or inherited version instead:

typed Value subclass: SupervisionTree
  // This class's own `do:` walks the enriched `nodes`, not `elements` —
  // `Enumerable`'s provision is dropped before it can conflict.
  uses: Enumerable(SupervisionNode) excluding: #(#do:)

overriding: acknowledges that a trait's provision replaces a method the class would otherwise inherit from its superclass — required because a trait provision never silently overrides an inherited method:

Record subclass: AuditRecord
  uses: Describable overriding: #(#printString)

Leaving out overriding: there is a compile error naming both sides and both fixes:

error: Describable provides `printString`, which AuditRecord would otherwise
       inherit from Record.
  hint: to use Describable's version, write
          uses: Describable overriding: #(#printString)
        to keep Record's version, write
          uses: Describable excluding: #(#printString)

printString and displayString inherited from Object/Value are exempt (they're cosmetic defaults every class is expected to replace); every other inherited selector — including equals:/hash — needs overriding:.

Two traits providing the same selector to one class is a compile error unless the class defines that selector itself or one uses: line excludes it:

Value subclass: Report
  uses: Labelled
  uses: Describable
  // error: `printString` is provided by both Labelled and Describable in Report.
  //   Define `printString` in Report, or exclude one:
  //     uses: Describable excluding: #(#printString)

Precedence

Flattening applies, highest precedence first: class body → trait provision → inherited. A class's own method always wins over a trait's provision, and a trait's provision — once acknowledged where needed (overriding: above) — wins over what the class would otherwise inherit. This is exactly what a hand-written method in the class body would mean; after flattening, there is nothing trait-shaped left for the type checker, dispatch, super, or hot reload to know about.

Requirements

Every required selector of a used trait must resolve on the class — from the class body, another used trait's provisions, or the superclass chain — or it's a compile error naming the missing selector:

Value subclass: Version
  uses: Comparable
  field: major = 0
// error: Version uses Comparable but does not implement required `<`
//   hint: Comparable requires `< other :: Self -> Boolean`

uses: on a protocol with no provisions is a hint, not an error or warning — it only checks the protocol's requirements at the class definition ("assert conformance here"); conformance itself stays structural (ADR 0068).

Which mechanism to use

Beamtalk has two ways to share behaviour, and each answers a different question:

MechanismAnswersExample
Superclass (X subclass: Y)"What is this?" — shares representation, state, and a place in the class hierarchyInteger/Float are Numbers
Protocol with provisions (uses:)"What capability does this have?" — derived from a few required methods, usable across unrelated classes and class kindsDateTime, Duration, Uuid, String all uses: Comparable despite sharing no common ancestor below Object

A superclass spends the class's one superclass slot and claims a kinship ("DateTime is-a Magnitude") that may not be true — DateTime, a Duration, and a Uuid share only that they can be ordered, not what they are. A protocol with provisions gives capabilities their own home and works across the class-kind wall (an Actor can use a trait a Value also uses, Enumerable above being one). A method added to a class you do not own is not a fourth mechanism: cross-file extension methods were removed (ADR 0152), so write the operation on a class of your own that takes the value (Shout of: aString).

Traits across the class kinds

An Actor wanting enumeration over what it holds needs its trait's provisions to work by snapshot, not an internal iterator — a block passed through a self-send to an actor loses ^ and captured-local writes (BT-3580). Enumerable(E) (stdlib/src/enumerable.bt) is written this way: its one requirement is elements -> List(E), and every provision (size, isEmpty, isNotEmpty, do:, inject:into:, select:, collect:, reject:, detect:, detect:ifNone:, anySatisfy:, allSatisfy:, noneSatisfy:, includes:, count:) forwards to the matching List primitive over that snapshot — no block ever crosses a self-send, so every provision runs in the caller's process regardless of whether the receiver is a Value or an Actor.

Collection does not uses: Enumerable itself (its own select:/ collect: already answer Self via the species pattern, richer than Enumerable's plain List(E)), but gains elements -> List(E) => self asList so every List, Set, Array, … conforms to Enumerable structurally, with no uses: needed.

Provisions are instance-side only in v1 (class sel … => in a protocol is rejected). An Object subclass: (no instances) that composes a trait is not an error, but gets nothing useful from it: the provisions flatten onto a class that will never be instantiated. Class-side provisions are a post-v1 item, tracked in BT-3595.

Reflection

DateTime usedProtocols                        // => [#Comparable]
DateTime usesProtocol: #Comparable             // => true
DateTime usesProtocol: #Printable              // => false
Protocol providedMethods: #Comparable          // => [#between:and:, #min:, #max:, #>, #<=, #>=]
Protocol usersOf: #Comparable                  // => [DateTime, Duration, Uuid, String]
(DateTime >> #between:and:) origin             // => Comparable
(DateTime >> #<) origin                        // => nil  (class's own method)

usedProtocols is distinct from protocols (ADR 0068's structural conformance query, § Runtime Protocol Queries above): a class can structurally conform to a protocol it never uses:, and usedProtocols answers only what it actually composes via uses:. allUsedProtocols walks the superclass chain too. CompiledMethod >> origin names the protocol a method was flattened from, or nil for a method the class wrote itself.

Editing a loaded protocol file's provisions and reloading it (ProtocolName reload) atomically recompiles and hot-swaps every loaded, source-backed user together — all-or-nothing: if any user's recompile fails against the edited protocol, nothing installs and the error names the failing user (ADR 0127 §11).

At the REPL, Describable >> summary => … adds or replaces a provision in the protocol's own source, and Describable removeSelector: #summary removes one. Both run through the same all-or-nothing re-expansion of every user, are recorded in the ChangeLog against the protocol (so Workspace flush writes the protocol file), and are refused for stdlib protocols. This is a live-image edit only: put a provision in a .bt file by writing it inside the Protocol define: body.

Two-Protocol String Model (Debug / Display)

Beamtalk follows a two-string-protocol model (ADR 0094), mirroring Rust's Debug / Display split:

String demonstrates the Debug/Display split directly: "hi" printString → "\"hi\"" (quoted, Debug) while "hi" displayString → hi (plain, Display).

Default printString forms by class kind

The a/an article prefix (the old a Point / ungrammatical a Integer default) is removed entirely. The default printString now takes one of four visually distinct forms, one per kind of thing:

Class kindDefault printStringExample
Value (immutable data)ClassName(field: value, ...) — class-headed, labelled fields, in sorted field orderPoint(x: 3, y: 4); no fields → Point()
Actor (live process)Actor(ClassName, pid) — kind-headed, positionalActor(Counter, 0.123.0)
Supervisor (supervising process)Supervisor(ClassName, pid) / DynamicSupervisor(ClassName, pid)Supervisor(WebApp, 0.200.0)
Object (plain reference)bare ClassName, or a class-defined formFileHandle, or e.g. #Pid<0.123.0> for raw primitives

Value forms carry field: labels while process forms are positional; the process heads (Actor / Supervisor / DynamicSupervisor) are reserved kind words no user Value class may shadow, so the two shapes are unambiguous. Raw platform primitives (Pid, Port, Reference, Tuple) keep their Erlang-native #Pid<…> / #Port<…> rendering — they are Erlang terms.

Nested Value fields expand recursively (so Line(from: Point(x: 0, y: 0), to: Point(x: 3, y: 4)) shows in full), each rendered via its own printString (Debug form — strings stay quoted), bounded by depth (default 5), width, and total-length caps with a cycle guard; truncated positions render as ....

Printable Protocol and Display Methods

The Printable protocol is the standard contract for objects that can represent themselves as strings. It requires two methods:

Most stdlib classes conform automatically because Object provides a default printString (the bare class name, or the structural ClassName(field: value, ...) form for Value subclasses) and most subclasses implement asString. Custom classes only need to implement these two methods to conform:

Value subclass: Point
  field: x = 0
  field: y = 0

  // Human-readable
  asString -> String => "({self.x}, {self.y})"

  // Developer-readable (REPL display)
  printString -> String => "Point({self.x}, {self.y})"

displayString is not part of Printable (deferred per ADR 0094 §5), and inspect is not part of any protocol — so the two-protocol changes leave protocol conformance unaffected.

The related display methods on Object are:

MethodBehaviour
asStringHuman-readable string conversion (override per class)
printStringDebug representation — self-describing, structural; the REPL default and what nested rendering uses
displayStringDisplay representation — the string-interpolation {...} hook; defaults to printString, override for a natural human form
inspectOpens an Inspector cursor on the receiver (Inspector on: self) — a navigable, drillable view (ADR 0095). For the structural Debug string, use printString.
show: valueWrite value to Transcript (returns self)
showCr: valueWrite value to Transcript followed by newline (returns self)

show: and showCr: are convenience methods on Object that delegate to the Transcript class-side facade (ADR 0129). Inside an interactive workspace the output goes to the REPL's transcript; everywhere else (beamtalk run, beamtalk test, releases) it is one plain Logger notice per call in the [beamtalk, user, transcript] domain, so they are always safe to call and return self. Programs should prefer Logger or Console; Transcript recent and Transcript clear are workspace-only and raise no_workspace elsewhere:

// Cascaded output
Transcript show: "Hello"; cr; show: "World"

// show:/showCr: on any object — nil-safe
42 show: "value: "
42 showCr: "hello world"

Transcript show: accepts any Printable value, so custom classes that conform to Printable work directly with Transcript show: without manual asString conversion.

Navigable Inspector (ADR 0095)

printString renders an object to one string. The Inspector lets you navigate into it — drill through fields, render across surfaces (REPL text tree, MCP/browser wire form), and re-snapshot live actor state. anObject inspect is the shorthand for Inspector on: anObject; it returns a cursor, not a string.

i := (Point x: 3 y: 4) inspect      // an Inspector cursor (#value kind)
i fields                            // the drillable InspectorField records (x, y)
i at: #x                            // Result(Inspector) — a child cursor on the value 3
(i at: #x) unwrap subject           // => 3
i printString                       // an indented text tree (Inspector(Point) + fields)

One polymorphic class, four kinds. A single Inspector carries a kind tag rather than a subclass per kind — classification lives in the runtime shim:

kindSubjectFields are…
#valuean immutable Value (or scalar)its slots, in ADR 0094 sort order (#slot)
#actora live actora lazy, timeout-guarded sys:get_state snapshot of its state
#collectionList/Array/Set/Dictionary/Baga window (page size 50) of #element / #association fields
#foreigna non-Beamtalk OTP processbest-effort process_info + a guarded state snapshot (#processInfo)

A wedged, dead, or non-sys actor degrades to a single #status: #unavailable field — it never crashes.

Navigation is immutable. Every navigation message returns a new cursor, so a UI can hold several at once:

MessageReturns
fieldsList(InspectorField) — the current window of drillable fields
at: keyResult(Inspector) — a child cursor on that field's value (#no_such_field on a miss)
parent / rootthe parent cursor / the top of the drill path (nil parent at the root)
paththe breadcrumb of drilled keys from the root
refresha fresh cursor on a newly-captured snapshot (the original is unchanged)
sizethe cheap full element count (for #collection), else the field count
page: na new cursor on the n-th window (1-based) of a large collection
printString / printStringExpanded: depththe indented text tree (depth 1 = immediate fields)
asDictionaries / asDictionarythe typed cross-surface wire form (one dict per field / the cursor envelope)

Each InspectorField is an immutable Value record with name (the navigation key), label, value, kind, and drillable (isLeaf is its negation).

evaluate: is values-only. On a #value cursor, i evaluate: "self x + self y" compiles and runs the expression with self bound to the inspected value, returning a Result — failures are Result error:, never a raise. The one exception is a ^ (non-local return) from a block captured elsewhere and run by the expression: it is control flow, not a failure, so evaluate: re-raises it to its home method (BT-3735). If the home method has already returned (a stale ^), nothing catches it and the enclosing eval/dispatch boundary reports it as a structured error. On an #actor cursor it returns Result error: with kind #actor_eval_unsupported (actor evaluate-in-context is a deferred §7 follow-up). Live updates are poll-only: re-issue refresh.

i := (Point x: 3 y: 4) inspect
(i evaluate: "self x * 10") unwrap        // => 30
(i evaluate: "self nonesuch") isError     // => true  (a Result error:, not a crash)

Deferred §7 seams (not in v1): actor evaluate-in-context (live routing), per-class inspectorFields custom views, sealedFromInspection, and push live updates (poll-only for now).


Union Types and Narrowing (ADR 0068)

Union Types

Union types express that a value may be one of several types:

// All members must respond to the message
x :: Integer | String := getValue
x asString             // Both Integer and String have asString
x size                 // Warning: Integer does not respond to 'size'
x + 1                  // Warning: String does not respond to '+'

The nullable pattern (String | nil) is the most common union — Beamtalk's Option/Maybe type:

name :: String | nil := dictionary at: "name"
name size              // Warning: Nil does not respond to 'size'

Similarly, false in type position resolves to False — used for Erlang FFI patterns:

entry :: Tuple | false := ErlangLists keyfind: key

Singleton members. Singleton symbol types (#foo, a subtype of Symbol) may appear in any type position — including unions — to express a closed set of atom values:

// a parameter that is an Integer or the sentinel #infinity
withTimeout: ms :: Integer | #infinity => ...

// a closed enum of singletons
restart: policy :: #temporary | #transient | #permanent => ...

A singleton receiver resolves methods against Symbol's protocol — #infinity asString infers String, and an unknown selector produces a DNU hint naming the singleton (e.g. #infinity does not understand 'frobnicate'). Equality comparisons (=:=, ==, /=, =/=) are excluded from this redirect so statically-decidable comparison hints still fire.

Discriminate a singleton union with =:= (identity) and the branches narrow — see Control Flow Narrowing.

Difference and Intersection Types (\ / &)

Beyond | (union), type annotations support two more set-theoretic operators (ADR 0102):

// "any Symbol except #north" — a co-finite atom set
tag :: Symbol \ #north := #south

// chained difference — left-associative, same as subtracting a union:
// equivalent to "any Symbol except {#north, #south}"
heading :: Symbol \ #north \ #south := #east

// union binds looser than difference: `Integer | Symbol \ #foo` is
// `Integer | (Symbol \ #foo)`, not `(Integer | Symbol) \ #foo`
withSentinel: ms :: Integer | Symbol \ #infinity => ...

// intersection: class ∩ protocol (ADR 0068's operator, now general)
describe: value :: Integer & Printable -> String => value asString

// chained intersection — left-associative, same tier as `\`
requires: value :: A & B & C => ...

Precedence (lowest-binding to highest), all only inside a type annotation — & and \ remain ordinary binary message selectors in value position, unaffected:

OperatorMeaningBinding
|unionlowest
&intersectionmiddle
\differencemiddle (left-assoc, same tier as &)
(atomic type)class name / singleton / generichighest

So Integer | Symbol \ #foo parses as Integer | (Symbol \ #foo) — \ binds tighter than |. Within one operator, chains are left-associative: Symbol \ #a \ #b parses as (Symbol \ #a) \ #b, and A & B & C parses as (A & B) & C.

Grouping parentheses. (...) is a grouping operator inside a type annotation, just as in value expressions (in addition to its generic-argument use, Result(T, E)). A group wraps any annotation — unions, &/\ chains, generics — and groups nest. Grouping is purely syntactic: the parenthesised annotation is the same annotation, so (Integer) means Integer, and (A | B) | C is the same flat three-member union as A | B | C.

// subtract a whole union in one step — equivalent to the chain
// `Symbol \ #a \ #b`, which the algebra normalises to the same result
tag :: Symbol \ (#a | #b) := #c

// a grouped difference as a union member (parens redundant here — `\`
// already binds tighter than `|` — but allowed)
withSentinel: ms :: Integer | (Symbol \ #infinity) => ...

Grouping is also how you mix & and \ in one annotation: mixing them in the same chain without parentheses is a deliberate parse error, not a left-associative fallback — A & B \ #c is rejected with "Cannot mix & and \ in a type annotation without parentheses; parenthesise to disambiguate", because (A & B) \ #c and A & (B \ #c) differ and neither reading is obviously the intended one. Parenthesise the reading you mean:

// intersect first, then subtract
narrow -> (A & B) \ #c => ...

// subtract first, then intersect
narrow -> A & (B \ #c) => ...

The lexer also greedily merges \\ (two backslashes) into the Smalltalk modulo selector, so a doubled backslash in type position — the natural typo for \ — gets a targeted diagnostic ("did you mean \?") instead of a confusing generic parse error.

Difference types show up in Control Flow Narrowing too: the false branch of a singleton equality test (x =:= #foo) narrows x to Symbol \ #foo, and hover displays that co-finite type directly.

Named Type Aliases (type Declarations) (ADR 0108)

A type declaration names an existing type annotation for reuse across signatures:

/// How a supervised child restarts after exit.
type RestartStrategy = #temporary | #transient | #permanent

type OptionalString = String | Nil
type JsonKey = String | Symbol
type Timeout = Integer | #infinity
type PublicTag = Symbol \ (#reserved | #internal)
type PrintableInt = Integer & Printable

Transparent, not nominal. RestartStrategy and #temporary | #transient | #permanent are the same type — a reference to the alias expands to its right-hand-side annotation everywhere type annotations are resolved: parameter types, return types, typed locals, both sides of |/\/&, narrowing, and match:/matchExhaustive: exhaustiveness. Two aliases with the same expansion are interchangeable, and there is no runtime tag distinguishing them — a RestartStrategy value is the atom temporary, exactly the value a hand-written union annotation would carry. A type declaration is erased entirely at compile time: no BEAM module, no runtime object, no live process.

type Direction = #north | #south | #east | #west

Object subclass: Compass
  heading: h :: Direction =>
    h matchExhaustive: [
      #north -> 0;
      #south -> 180;
      #east  -> 90;
      #west  -> 270
    ]

  defaultHeading -> Direction => #north

type is a contextual keyword. It is recognized only at top-level declaration position via a three-token lookahead (type + uppercase identifier + =). It remains a legal identifier everywhere else — type := 5, foo type, type printString are all unaffected.

Exhaustiveness is inherited, not new. Because an alias reference expands to its structural annotation before any checker runs, the advisory match: warning and asserted matchExhaustive: error apply exactly as they would to the spelled-out union — no new exhaustiveness machinery. Adding a member to the alias declaration makes every matchExhaustive: over it non-exhaustive in one edit:

heading match: [
  #north -> 0;
  #south -> 180;
  #east  -> 90
]
// ⚠ Warning: non-exhaustive match: `#west` is not handled (residual type: `#west`)

heading matchExhaustive: [
  #north -> 0;
  #south -> 180;
  #east  -> 90
]
// ⛔ Error: non-exhaustive matchExhaustive: `#west` is not handled (residual type: `#west`)

A value outside the named union is flagged the same way an inline union would be:

p :: RestartStrategy := #premanent
// ⚠ Warning: Type mismatch: declared as RestartStrategy
//    (#temporary | #transient | #permanent), got #premanent

Exported by default, like classes and protocols. A type declaration is visible to any package that depends on the declaring one, unless marked internal:

internal type ParserState = Integer | String

An internal alias is package-private, following the same model as class- and method-level internal (ADR 0071): usable within the declaring package, a compile error to reference from outside it. Because aliases are transparent, referencing an internal alias from a public signature is also a compile error even within the same package (the same "leaked visibility" rule 0071 already applies to internal classes) — and so is reaching one through the expansion of a public alias, since a public alias has no "internal signature" escape hatch of its own:

internal type Priv = Integer
type Pub = Priv | String
// ⛔ Error: Internal type alias 'Priv' appears in the expansion of
//    public type alias 'Pub'

Constraints:

Erlang interop. Codegen emits a named Erlang -type attribute for each alias declared in a module, and method -spec attributes reference it via user_type instead of expanding to any(). Erlang/Elixir consumers of a compiled Beamtalk module see idiomatic Dialyzer types (e.g. -type 'Timeout'() :: integer() | 'infinity'.). See Dialyzer Spec Generation for details.

Tooling. The LSP offers completions, go-to-definition, find-references, and hover for alias names in .bt files. In the REPL, type declarations are accepted as input and persist for the rest of the session; declaring type Direction = ... at the prompt echoes the declared name (=> Direction), the same convention a class declaration echoes (Actor subclass: Counter → Counter); :help <Alias> renders the declaration, its expansion, and any doc comment. Stdlib-declared type aliases (e.g. RestartStrategy, Timeout) are available automatically in a fresh REPL session — :: typed locals referencing them resolve without a prior declaration, and :help RestartStrategy shows Declared in: stdlib. A session-declared type with the same name shadows the stdlib alias. The System Browser and the VS Code Workspace Explorer sidebar list declared aliases in a "Type Aliases" section alongside Classes and Protocols. See docs/development/surface-parity.md for the full cross-surface matrix.

Shape Types (ADR 0147)

A shape is a structural type for a dictionary whose symbol keys each have their own value type. It is written like the map literal it describes and is usable anywhere a type is: annotations, type aliases, generic arguments and unions.

type Point = #{#x => Integer, #y => Integer}

p :: Point := #{#x => 1, #y => 2}
p at: #x                          // Integer
p at: #z ifAbsent: [0]            // ⚠ `#z` is not a key of Point
q :: Point := #{#x => 1}          // ⚠ missing required key `#y`

Required and optional keys. #k => T is a required key. ?#k => T is an optional key: it may be missing. Optional is a property of the key, not the value: ?#k => T means the key may be absent, while #k => T | Nil means it is present and may hold nil.

type WebSocketOptions = #{
  ?#maxFrameSize => Integer,
  ?#compress => Boolean,
  ?#deflateOptions => Dictionary(Symbol, Object)
}

Closed and open. A shape is closed by default: a key it does not name is a warning. A trailing ... makes it open, so other keys may be present (#{#kind => Symbol, ...}). Use an open shape for maps that flow through layers that add their own keys.

Subtyping with Dictionary. Shapes are covariant in their value types, because dictionaries are immutable.

Literal inference. A map literal whose keys are all symbol literals infers a closed shape, nested literals inferring nested shapes. opts := #{#body => "{}", #timeout => 5000} has type #{#body => String, #timeout => Integer}, so passing opts to a shape-typed parameter is checked key by key. Any other literal infers Dictionary(K, V).

Shape-aware operations. Only these use the per-key types, and the key must have a singleton symbol type (a literal #k, or a local bound to one):

OperationRequired keyOptional keyKey not in shape
at: #kTT (raises at run time if absent)closed: warning; open: Object
at: #k ifAbsent: [b]TT | Bclosed: warning; open: Object | B
at: #k ifPresent: [:v | ...]block gets Tblock gets Tclosed: warning; open: block gets Object
map pattern #{#k => v}v :: Tv :: Tclosed: warning; open: v :: Object
at: #k put: vshape with #k => typeof(v), requiredsameshape gains #k, required

Every other message (keys, do:, collect:, removeKey:, merge:, ...) treats the shape as Dictionary(K, V). On a union receiver (S | Nil) a keyed read answers the union of each member's result.

Diagnostics are warnings (ADR 0100), and name the offending key: a literal checked against a shape reports a missing required key, an unknown key in a closed shape, or a wrong value type. A misspelt key gets a suggestion: #maxFramSize against a closed #maxFrameSize reports key `#maxFramSize` is not named by the closed expected shape — did you mean `#maxFrameSize`? when the target key is optional, and missing required key `#maxFrameSize` — did you misspell it as `#maxFramSize`? when it is required.

FFI mapping. The spec reader maps Erlang map types with atom keys to shapes: k := T becomes #k => T, k => T becomes ?#k => T, and a general key field (atom() => term()) adds a trailing .... Maps with no atom keys stay Dictionary. (Erlang uri_string) parse: url therefore answers a closed shape with seven optional keys, or the error tuple. Value types are whatever the spec reader already produced, so unicode:chardata() fields stay loose.

Runtime. None. Shapes are erased like every other annotation, a shape in a signature still emits map() in the Erlang -spec, and a shape-typed value is an ordinary Dictionary. A shape is a claim about maps the program builds itself (options, config) or that a trusted FFI spec describes. It does not validate anything: keep runtime validators for value ranges and for callers that build the map dynamically.

Class metadata. A shape field is recorded as Dictionary in class metadata (BT-4788): the metadata is stored as atoms, which are limited to 255 bytes, and a shape's text can exceed that. Code in the defining package sees the shape; a package that reads the class from its compiled metadata sees Dictionary, so a key the shape would have checked is not checked there. Declare a type alias in the package's own source if its users need the shape.

What to shape. Shape leaf option sets (WebSocketOptions). Keep shared or generic option bags, and any map whose keys are added at runtime, as Dictionary(Symbol, Object).

External data. Do not use shapes for JSON or YAML. Their keys are strings (shapes take symbol keys only) and their types are erased, so a shape over decoded data is an unchecked claim that looks like a guarantee. Parse external data into Value classes at the boundary instead.

Tooling. Redefining a shape alias re-checks its use sites through the same hot-reload trigger as any alias. The LSP offers key completion after at: # on a shape-typed receiver and hover showing a key's type. In the REPL, type Point = #{...} echoes Point and :help Point shows the expansion.

Control Flow Narrowing

When the type checker recognises a type-testing pattern followed by ifTrue: / ifFalse:, it narrows the variable's type inside the block scope:

// class identity check — narrows to exact class
process: x :: Object =>
  x class =:= Integer ifTrue: [
    x + 1          // x is Integer here — has '+'
  ]
  x + 1            // x is Object here — no narrowing outside the block

// kind check — narrows to class including subclasses
process: x :: Object =>
  x isKindOf: Number ifTrue: [
    x abs           // x is Number here
  ]

// early return narrows the rest of the method
validate: x :: Object =>
  x isNil ifTrue: [^nil]
  x doSomething    // x is non-nil for the remainder

// isKindOf: guard-and-return also narrows the rest of the method (BT-2825)
render: coll :: Printable | Nil -> String =>
  coll isNil ifTrue: [^""]
  (coll isKindOf: List) ifFalse: [^""]
  items :: List := coll   // no `@expect type` needed — coll is List here
  items inject: "" into: [:acc :item | acc ++ item asString]

Supported narrowing patterns:

PatternNarrows toScope
x class =:= Foo ifTrue: [...]x is Foo in true blockTrue block only
x isKindOf: Foo ifTrue: [...]x is Foo in true blockTrue block only
x isKindOf: Foo ifFalse: [...]x is T \ Foo in false blockFalse block only
x isKindOf: Foo ifFalse: [^...]x is Foo after the statementRest of method
x isKindOf: Foo ifTrue: [^...]x is T \ Foo after the statementRest of method
x isKindOf: Foo ifTrue: [^...] ifFalse: [...]x is T \ Foo after the statementRest of method
x isNil ifTrue: [^...]x is non-nil after the statementRest of method
x isNil ifTrue: [self error: "..."]x is non-nil after the statementRest of method
x isNil ifFalse: [...]x is non-nil in false blockFalse block
x isNil ifFalse: [^...]x is nil after the statementRest of method
x isNil ifTrue: [^...] ifFalse: [...]x is non-nil in false blockFalse block
x ifNotNil: [:v | ...]v is non-nil in blockBlock only
x ifNil: [...] ifNotNil: [:v | ...]v is non-nil in notNil blockNotNil block
x notNil ifTrue: [...] / x notNil ifFalse: [^...]same as x isNil with the branches swapped: x is non-nil in the true block / after the statementTrue block / rest of method
x notNil and: [...]x is non-nil in block, including nested block-argument positionsBlock only
x isNil or: [...]x is non-nil in the block (it runs only when x isNil was false)Block only
(a isNil or: [b isNil]) ifTrue: [^...]every tested var is non-nil after the statementRest of method
(a isNil or: [b isNil]) ifFalse: [...]every tested var is non-nil in false blockFalse block
(a notNil and: [b notNil]) ifFalse: [^...]every tested var is non-nil after the statementRest of method
(a notNil and: [b notNil]) ifTrue: [...]every tested var is non-nil in true blockTrue block
(p and: [x notNil]) ifTrue: [...] (p is any condition the checker does not read)x is non-nil in true blockTrue block
(x isNil or: [p]) ifTrue: [^...] / (x isNil or: [p]) ifFalse: [...]x is non-nil after the statement / in the false blockRest of method / false block
(x notNil and: [k isKindOf: Foo]) ifTrue: [...]x is non-nil and k is Foo in true blockTrue block
(x notNil and: [y notNil and: [p]]) ifTrue: [...]x and y are non-nil in true blockTrue block
x isNil not ifTrue: [...], (k isKindOf: Integer) not ifTrue: [^...], (a isNil or: [b isNil]) not ifTrue: [...]not swaps the true and false facts, so each narrows as its un-negated dual would; it composes with and: / or: in either positionTrue block / rest of method
[x notNil] whileTrue: [...], [n notNil and: [p]] whileTrue: [...], [n isNil] whileFalse: [...]the condition block's last expression narrows the loop body, as ifTrue: / ifFalse: would; only for variables the body never assigns. A self.<field> test narrows the body too, until a self-send or a write to the field, as in a branch arm (BT-4713, BT-4788). Not narrowed after the loopLoop body only
c := x notNil. c ifTrue: [...] (also ifFalse:, not, and: / or:, whileTrue:, post-guard)a local assigned a condition stands for what that condition proves. Dropped when the local or any variable it tests is reassigned, when a block assigns either, and for self.<field> tests; an alias never proves more than the inline test (BT-4714)Branch arms / loop body / method remainder, as for the inline test
(p or: [x notNil]) ifTrue: [...], (x notNil or: [p]) ifTrue: [...], (x isNil and: [p]) ifFalse: [...]no narrowing — the other side may have decided the answer—
x =:= #sym ifTrue: [^...]x is T \ #sym after the statementRest of method
x == #sym ifTrue: [^...]x is T \ #sym after the statementRest of method
x respondsTo: #sel ifFalse: [^...]x narrows post-guardRest of method
(x =:= false) ifTrue: [^...]x is T \ False after the statementRest of method
(x == true) ifTrue: [^...]x is T \ True after the statementRest of method
(x =:= false) ifTrue: [...] ifFalse: [...]x is False in the true block, T \ False in the false blockEach block
(x =:= nil) ifFalse: [...] / (x =:= nil) ifTrue: [^...]same as x isNilFalse block / rest of method
(x =/= nil) ifTrue: [...] / (x =/= nil) ifFalse: [^...]same as x notNil: x is non-nil in the true block / after the statementTrue block / rest of method
x isError ifTrue: [...], x isOk ifFalse: [...], x ifError: [:e | ...], the ifError: block of x ifOk:ifError:a local x :: Result(T, E) is known to be the error variant, so ^x fits any Result(U, E) return; sends on x are typed as before (BT-5290)That block only

Known gaps (accepted, BT-4788). The checker misses these on purpose; each is a missed warning or a wider type, never a crash.

The diverging-guard pattern (isNil ifTrue: [self error: "..."]) recognises any block whose body infers as Never — including calls to error:, notImplemented, or any -> Never method — not just non-local returns (^). Narrowing also works on self.field reads: inside self.field isNil ifFalse: [...], the field narrows to non-nil within the block.

notNil and: (BT-2872): x notNil and: [...] narrows x to non-nil for the whole block argument — not just where x is a further send's receiver, but in any nested position, including as an argument to a binary send inside a further-nested block (local notNil and: [local > 0 and: [5 >= local]] narrows local inside 5 >= local too). The narrowing does not survive past the block — a later unguarded use of x after the and: send is unaffected.

Mixed and: / or: chains (BT-4710): every condition has two sets of facts — what is true of each variable when it answers true, and when it answers false. A single test (isNil, notNil, isKindOf:, …) contributes its own narrowing. a and: [b] is true only when both are, so it carries both sides' true facts (b is checked under a's); it is false when either is, so only a variable both sides narrow stays narrowed, to the union of the two types. or: is the dual. c not answers the same two sets swapped (BT-4711). A part the checker does not understand (a plain Boolean, a multi-statement block, a call) contributes no facts but does not stop the rest of the chain from narrowing. ifTrue:, ifFalse:, ifTrue:ifFalse:, early return and the lazy and: / or: blocks all read the same facts.

Combined nil-guards (BT-4107): an or:-chain of isNil tests narrows every tested variable — (a isNil or: [b isNil]) ifTrue: [^nil] proves both a and b non-nil afterwards (or: is false only when both disjuncts are false), and both are non-nil inside the ifFalse: arm. Dually, (a notNil and: [b notNil]) ifFalse: [^nil] proves both non-nil afterwards, and both are non-nil inside the ifTrue: arm. The complementary directions are disjunctive and never narrow: an or: guard that holds (or an and: guard that fails) only proves some variable is nil, not which. As a consequence, a lone a notNil test narrows too (ifFalse: [^...] post-guard, ifTrue: in-branch).

isKindOf: guard-and-return (BT-2825): the same diverging-guard treatment isNil gets also applies to isKindOf: — (x isKindOf: Foo) ifFalse: [^default] proves x is Foo for the rest of the method, and (x isKindOf: Foo) ifTrue: [^default] proves x is T \ Foo. This also closes a related gap: when x's declared type is a Protocol (e.g. Printable) and Foo is a concrete class, the narrowed type collapses to the bare Foo — a runtime isKindOf: Foo check is a stronger proof than the protocol annotation, so the narrowed value is assignable to a Foo-typed local without an @expect type escape hatch.

nil equality (BT-4712): x =:= nil and x == nil narrow exactly like x isNil; x =/= nil and x /= nil narrow like x notNil. Either operand order works (nil =:= x), and the tests narrow inside and: / or: blocks too. nil is the only instance of UndefinedObject, so the equality test and isNil are the same fact.

Boolean-literal equality (BT-4638): x =:= false and x =:= true (also ==, and either operand order) narrow exactly like x isKindOf: False / x isKindOf: True, because true and false are the only instances of the sealed classes True and False. (x =:= false) ifTrue: [^0] removes False from x afterwards (Integer | False becomes Integer). The negated spellings /= and =/= are not narrowed. Testing a variable whose inferred type can never be that boolean also produces the "comparison can never be true" hint: after n := 3, (n =:= false) reports that Integer is never a False. As with isKindOf:, a declared (annotated) type does not fire the hint, since annotations are unverified promises and a defensive guard against them is legitimate.

Singleton-equality guard-and-return (BT-3369): the same diverging-guard treatment extends to singleton-equality checks — x == #undefined ifTrue: [^false] proves x is not #undefined for the rest of the method, narrowing to T \ #undefined. Both == and =:= are accepted (they are provably equivalent for atom/symbol comparisons). respondsTo: guards also carry forward: (x respondsTo: #foo) ifFalse: [^default] narrows x post-guard.

Conditional Return Type Inference

ifTrue:ifFalse: on Boolean (and True/False) is declared as Block(R), Block(R) -> R — the type checker unifies both arms to a common return type. The result of a conditional expression is now statically typed rather than Dynamic:

x := condition ifTrue: [42] ifFalse: [0]
// x is inferred as Integer (not Dynamic)

result isOk ifTrue: [result unwrap] ifFalse: [default]
// inferred as the common type of both arms

The solo forms — ifTrue: [...] and ifFalse: [...] — can't unify to a bare R the way the two-armed form does: Boolean>>ifTrue:/ifFalse: are deliberately declared with no return type, because on an unnarrowed Boolean receiver the checker can't statically prove whether True or False handles the send, and the sibling override (e.g. False>>ifTrue:) never invokes the block — it returns self instead. Rather than collapsing all the way to Dynamic, a solo send infers the union of that Boolean self-branch and the block's own return type (BT-2868):

flag :: Boolean := x > y
flag ifTrue: [1]
// inferred as Boolean | Integer, not Dynamic

flag ifFalse: ["no"]
// inferred as Boolean | String

A receiver already narrowed to exactly True or False (e.g. inside an x isKindOf:-style guard, or after control-flow narrowing) is unaffected — True>>ifTrue:/False>>ifFalse: declare concrete -> R return types and resolve normally, without the extra Boolean union member.

ifNil:ifNotNil: (and ifNotNil:ifNil:) on nullable receivers also infers a branch-union return type — typeof(nilBranch) | typeof(notNilBranch). A branch containing a non-local return (^) contributes Never, leaving only the surviving branch's type:

name :: String | nil := dictionary at: "name"
result := name ifNil: ["unknown"] ifNotNil: [:n | n size]
// result is inferred as String | Integer

value := name ifNil: [^nil] ifNotNil: [:n | n]
// value is inferred as String (nil branch contributes Never, skipped)

The solo forms — ifNil: [...] and ifNotNil: [:v | ...] — infer the same way, unioning the block's return type with the "self" branch (executed when the nil-check doesn't match):

name :: String | nil := dictionary at: "name"
name ifNil: ["unknown"]
// inferred as String (T | R, where T = String and R = String both dedup)

count :: Integer | nil := dictionary at: "count"
count ifNil: ["none"]
// inferred as Integer | String (T | R)

name ifNotNil: [:n | n size]
// inferred as Integer | Nil (R | Nil)

Union + Narrowing Compose

name :: String | nil := dictionary at: "name"
name isNil ifTrue: [^"unknown"]
name size              // name is narrowed to String — nil eliminated by early return

Control Flow and Mutations

Beamtalk supports Smalltalk-style control flow via messages to booleans and blocks, with full mutation support via a universal state-threading protocol (ADR 0041).

How It Works

The compiler uses a two-tier optimization for block mutations:

Local variable mutations work in the blocks of control-flow messages (the table below, conditionals, on:do:/ensure:, Result tryDo:), written directly as the message's argument, in every method kind and in the REPL, including when the construct is an operand of a larger expression. A block that assigns a captured local and escapes (stored, returned, or passed to any other method, the actor's own methods included) is a compile error (ADR 0133, which amends ADR 0041's "local mutations work in all blocks"; see What Works and What Doesn't). The Tier 2 protocol remains inside the stdlib's own collection messages for dynamic receivers. Field mutations (self.x :=) in an actor instance method work in every block, stored or not (Actor Blocks See Live State). In value-type methods they require control-flow context and are a compile error in stored closures.

Control Flow Constructs

These message sends are Tier 1 optimized — the compiler generates inlined tail-recursive loops with zero overhead:

ConstructExampleMutations Allowed
ifTrue: / ifFalse: / ifTrue:ifFalse: / ifFalse:ifTrue:flag ifFalse: [n := 0] ifTrue: [n := 1]✅
whileTrue: / whileFalse:[count < 10] whileTrue: [count := count + 1]✅
whileTrue / whileFalse (unary: the receiver block is condition and body, so it runs at least once)[self.count := self.count + 1. self.count < 10] whileTrue✅ (below)
timesRepeat:5 timesRepeat: [sum := sum + n]✅
to:do:1 to: 10 do: [:n | total := total + n]✅
to:by:do: (any Number step; the block parameter is a Number, or an Integer for a statically-Integer step)1 to: 2 by: 0.5 do: [:x | total := total + x]✅
do:, collect:, select:, reject:items do: [:x | sum := sum + x]✅
inject:into:items inject: 0 into: [:acc :x | acc + x]✅

to:by:do: accepts a Float step, while to:by: (the Interval constructor) accepts only an Integer step and raises TypeError otherwise (BT-5217). So 1 to: 2 by: 0.5 do: [...] loops over 1, 1.5 and 2.0, but (1 to: 2 by: 0.5) do: [...] raises. The start of to:do: and to:by:do: must be an Integer: only Integer defines them, so 1.5 to: 3 do: [...] raises does_not_understand (BT-5235).

The unary [...] whileTrue / [...] whileFalse is the keyword loop with an empty body ([...] whileTrue: []), so its receiver follows the rule for a whileTrue: condition (BT-4313). A local written in a whileTrue:/whileFalse: condition threads in every method kind and at the REPL, the unary forms included, whatever the condition or body does (BT-4602): count := 0. [count := count + 1. count < 10] whileTrue leaves count at 10. The condition runs once more than the body. The one exception is a keyword loop whose body is not a block literal ([count := count + 1. count < 10] whileTrue: aBlock): the loop runs its condition as a closure, so a local written in it is a compile error (BT-4062); wrap the block value in a literal (whileTrue: [aBlock value]).

A repeat sent to a block literal is the loop [true] whileTrue: [...] (BT-4589), so its receiver is a loop body: the locals and REPL bindings it writes are carried from one iteration to the next, and are visible after a ^ ends the loop. An error that ends it follows the protected-region rule like any other loop.

ifFalse:ifTrue: is the two-branch conditional with the arms in the other order (BT-4991): c ifFalse: [a] ifTrue: [b] answers what c ifTrue: [b] ifFalse: [a] answers. With two literal block arguments that take no parameters, the compiler lowers it as that ifTrue:ifFalse:, so inlining, narrowing, local threading and ^ inside a block behave exactly as they do for ifTrue:ifFalse: (a ^ in one arm still uses the non-local-return throw/catch, as it does there). This holds for an untyped receiver too: the inline case sends the message only for a value that is not a Boolean. It does not apply to a self, super or class-reference receiver, or to the first message of a cascade; those, and any send with a block held in a variable, are ordinary sends, which Boolean answers. A receiver that is not a Boolean is sent ifFalse:ifTrue: as written, and the type checker resolves it under that selector, so a Boolean | C receiver loses the Boolean narrowing inside the arms.

Local Variable Mutations

// Simple counter
count := 0
[count < 10] whileTrue: [count := count + 1]
// count is now 10

// Multiple variables
sum := 0
product := 1
i := 1
[i <= 5] whileTrue: [
    sum := sum + i
    product := product * i
    i := i + 1
]
// sum = 15, product = 120, i = 6

// Collection iteration
numbers := #(1, 2, 3, 4, 5)
total := 0
numbers do: [:n | total := total + n]
// total = 15

// With index
result := 0
1 to: 10 do: [:n | result := result + n]
// result = 55 (sum of 1..10)

The rule (ADR 0133): a block may assign a variable it captured only where the compiler lowers the block in place, that is, as the block literal written directly as the argument (or, for value and the loops, the receiver) of a control construct or a compiler-known collection message. A block that escapes, by being stored in a variable, returned, placed in a collection literal, or passed to any other method (a user-defined method, a class or actor, a stdlib method outside the known list), may read captured variables but not assign them. The compiler reports the assignment, names how the block escapes, and lists the messages that do thread assignments. The idiom is to have the block answer the new value and assign it where the block is called:

// ❌ ERROR: `t` is assigned in a block passed to `twice:`, which is not a
//    construct the compiler threads it through
t := 0
Twice twice: [t := t + 1]

// ✅ The block answers the value; the caller assigns it
t := Twice twice: [t + 1]

// ✅ A construct the compiler threads
2 timesRepeat: [t := t + 1]

This departs from Pharo, where Twice twice: [t := t + 1] answers 2: it relies on a heap shared between a block and its home method, which the BEAM does not have (see docs/principles.html §4). Reads of captured variables, and ^ from any block, are unaffected. The same diagnostic is reported by beamtalk build, the REPL, the LSP and MCP.

Your own collection classes. The collection messages above (do:, inject:into:, collect:, select:, detect:ifNone:, anySatisfy:, …) thread a writing block literal for any receiver that implements do:, including your own class or actor: the compiler runs the block in place as a fold over the receiver's do:, whether that do: forwards to an inner List or walks by hand, and whether the other messages are the stdlib's or absent (ADR 0133, BT-3903). The exception is an actor's self do: (or super do:, or any of these messages) from inside its own method: that is a message to the actor's own method, so the block escapes and writing a captured local in it is a compile error (BT-3918). Every message but do: is checked first, at run time, against the receiver's class, and the write threads only when the class defines no collection message of its own: the sent message must resolve to the stdlib's own method, or to a provision of a stdlib trait such as Enumerable (judged by where the method comes from, not by the class that uses: it), and none of the collection messages above except do: may be a method outside the stdlib. The stdlib's collect:, select:, count:, eachWithIndex: and do:separatedBy: run through self inject:into: (and reject: through select:), so a class with its own inject:into: would have that override run by the plain send but skipped by the in-place fold. Any such override in the class or a package-local trait makes a writing send of any of these messages raise stateful_block_dispatch rather than silently running the fold over do: in its place; a receiver that does not respond to the message raises does_not_understand, as the plain send does (BT-3916). To thread a write through such a class, uses: Enumerable (the stdlib's provisions thread), define only do:, or compute the value without assigning from the block. A block passed to a message of your own (orders sumOf: [:o | total := ...]) is not covered; return the value from the block instead.

Field Mutations

Mutations to actor state (self.field) work the same way:

Actor subclass: Counter
  state: value = 0
  state: count = 0

  // Field mutation in control flow
  increment =>
    [self.value < 10] whileTrue: [
      self.value := self.value + 1
    ]
    self.value

  // Multiple fields
  incrementBoth =>
    [self.value < 10] whileTrue: [
      self.value := self.value + 1
      self.count := self.count + 1
    ]

Mixed Mutations

Local variables and fields can be mutated together:

processItems =>
    total := 0
    self.processed := 0
    
    self.items do: [:item |
        total := total + item
        self.processed := self.processed + 1
    ]
    
    ^total

What Works and What Doesn't

A block that assigns a captured local may not escape (ADR 0133, which made ADR 0131 §6's error the permanent rule). A block literal that assigns a local of the enclosing method (a Tier 2 block value, ADR 0041) may only be written where the compiler lowers it in place: as the block of a control-flow message (whileTrue:, do:, inject:into:, the conditionals, on:do:/ensure: with both blocks written in place, Result tryDo:, [...] value, and the handlers of a Dictionary's at:ifAbsent:, at:ifPresent: and at:ifPresent:ifAbsent: in a method body, a conditional or on:do: block, or a loop or fold body). A block that escapes is a compile error in every context (class, value-type and actor methods, and the REPL), reported at the assignment and naming the shape:

ShapeMessage
f := [t := t + 1]`t` is assigned in a block stored in `f`
^[t := t + 1]`t` is assigned in a block returned from `run`
self forEach: [:o | t := t + o]`t` is assigned in a block passed to `forEach:`, which is not a construct the compiler threads it through
self do: [:x | t := t + x] (in an actor)`t` is assigned in a block passed to `self do:`, which runs the actor's own `do:` method rather than the collection loop the compiler threads it through
Tally new: [:e | seen := seen + 1] (new: is process-bound)`seen` is assigned in a block passed to a class method (`new:`); it would run in another process
Erlang lists foreach: [:e | t := t + e] with: xs`t` is assigned in a block passed to Erlang `lists` `foreach:with:`, which calls it as a plain fun
#([t := t + 1])`t` is assigned in a block placed in a collection literal
xs collect: [:x | [t := t + x]]`t` is assigned in a block answered by the block of a collection operation
b ensure: [t := 9] (b a block value)`t` is assigned in a block of an `ensure:` whose blocks are not all written in place, which the compiler runs as a closure and does not thread it through

An on:do: or ensure: threads a write only when its protected block and its handler or cleanup are both block literals: with a block value in either position (b ensure: [t := 9], [t := 9] ensure: c) the compiler runs the literal block as a closure, so the write is the same error (BT-4430). Wrap the block value in a literal ([b value] ensure: [t := 9]); a ^ in such a block still returns from the method. This is the language rule, not a gap (ADR 0133, amendment BT-4430): on:do: and ensure: are in place only when both operands are block literals. An actor field write in such a block is fine (b ensure: [self.n := 9]): it writes the actor's live state. A stored block is an error however it is used later, a value send included; so is a self-send to a sealed method of an actor's own class, which ADR 0131 §6 (BT-3755) exempted and ADR 0133 retires, and so is a collection message (do:, inject:into:, ...) an actor sends to self or super inside its own method, which is a message to its own method rather than the inlined collection loop (BT-3918). A class method is said to run in another process when its selector is process-bound; a block passed to one that runs in the caller is reported like a block passed to any other method (ADR 0142). A block literal that assigns a captured local and is passed as an Erlang FFI argument (Erlang lists foreach: [:e \| t := t + e] with: xs) is the same compile error (BT-3917): Erlang calls it as a plain fun and the write would be dropped. Return the value from the block and use the call's result instead (ADR 0041 §Erlang Interop Boundary); a block that only reads captured variables is fine. The same holds for value-type object state: a block that assigns self.field in a value-type method and escapes is the same compile error, reported at the assignment as self.field (BT-3922; a Value subclass reports Cannot assign to slot instead, since value types are immutable). An actor field write in an escaping block is legal: the block writes the live state at home (ADR 0137). Reading captured variables and ^ inside an escaping block are unaffected, and so are writes to the block's own parameters and locals.

An actor block that reads a field may escape (ADR 0137; this retires the BT-3952 restriction of ADR 0133's amendment). In an actor instance method a block reads the actor's fields as they are when it runs, not when it was made; see Actor Blocks See Live State. The local-threading rows listed in validators/local_threading.rs remain until BT-3913 lowers them.

These lookup handlers are lowered inline, behind a runtime check that the receiver is a Dictionary: a handler that writes an outer local sent to anything else (an Ets, a value-type instance with its own at:ifAbsent:, a user class) raises a structured type_error instead of dropping the write. A receiver statically known not to be a Dictionary (self/super outside one, or an inferred type that is a known other class such as Ets) keeps the compile error. In a closure that is not inlined (a stored block, a block passed to another method) the enclosing block escapes, and in the REPL the handler is still a compile error.

error: `count` is assigned in a block passed to a class method (`new:`); it would run in another process
  = the block
  = a block that is stored, returned, or passed to a method the compiler does not lower in place
    may read captured variables but not assign them (ADR 0133). The messages that thread
    assignments, with the block written directly as the argument, are the control constructs
    (ifTrue:, ..., value:value:value:) and the collection messages (do:, ..., at:ifPresent:ifAbsent:)
  help: return the new value from the block and assign it where it is called:
        `count := ... new: [... count + 1]`

The note's list is generated from crates/beamtalk-core/src/state_threading_selectors.rs, the one list codegen reads.

// ❌ ERROR: `ap:` is not a construct the compiler threads the block through
count := 0
CvA ap: [count := count + 1]

// ✅ Return the value instead
count := CvA ap: [count + 1]

// ✅ Or use a control-flow message that threads locals
10 timesRepeat: [count := count + 1]

A block that escapes the method without being sent — returned via ^, implicit last expression, stored in a field, or placed in a collection literal — is the same error. A method whose last statement is a local assignment answers the assigned value (class, value-type and actor methods alike), so a block stored there is returned too; it is reported as stored:

error: `count` is assigned in a block returned from `makeCounter`
  help: once the block has left this scope, no later call of it can hand `count` back:
        keep the state in a field (`self.count := self.count + 1`) or return the new value
        from the block and assign it where the block is called
// ❌ ERROR: escaping stateful block
makeCounter =>
    count := 0
    ^[count := count + 1]      // returned — compile error

// ❌ ERROR: stored in a field
storeBlock =>
    count := 0
    self.block := [count := count + 1]

// ❌ ERROR: placed in a collection literal
listOfBlocks =>
    count := 0
    #([count := count + 1])

What works where (ADR 0131). A construct whose blocks write a local of the enclosing method (a local-threading producer) answers its value and keeps those writes. The writes are returned alongside the value and rebound in the enclosing frame, so the construct can sit wherever an expression can, not only as a statement. The constructs are the loops and collection messages in the table above (do:, collect:, inject:into:, eachWithIndex:, do:separatedBy:, keysAndValuesDo:, doWithKey:, anySatisfy:, allSatisfy:, detect:, detect:ifNone:), the conditionals (ifTrue:, ifNil:, and:/or:, ...), on:do:/ensure:, Result tryDo:, a block literal sent value, and Dictionary at:ifAbsent:, at:ifPresent: and at:ifPresent:ifAbsent:. The positions that work are:

// An operand-position construct: `+` sees the collect: result, and `t` keeps the writes
t := 0
n := (#(1, 2, 3) collect: [:x | t := t + x]) size + t
// n = 3 + 6 = 9, t = 6

// A sibling that reads the local before a later sibling rebinds it reads the old value
t := 0
r := t + ([t := t + 1. 1] on: Error do: [:e | 0])
// r = 0 + 1 = 1, t = 1

Specific forms:

In a value-type method, a do:, collect: or inject:into: that writes a field (self.m := ...) may sit inside the arm of a conditional (c ifTrue: [xs do: [:e | self.m := self.m + e]]): the arm is a frame whose fold hands its updated self to the statements after the conditional (BT-3844, BT-3854).

The protected-region rule. A local written inside the block of an on:do: or Result tryDo: that then raises is discarded: after the handler runs, the local has the value it had on entering the block. Writes made before entering the block are kept, and writes made by the handler itself (and by an ensure: cleanup) are kept. This holds in every method kind and in the REPL.

t := 0
(Result tryDo: [t := t + 1. 1 / 0]) isError   // => true
t                                             // => 0, the write inside the raising block is discarded

This is a deliberate departure from Pharo, where temporaries are shared cells and a write made before the raise survives. On BEAM the protected region's locals are a value that is returned only when the block completes. A block that does not raise keeps all its writes.

match: arms. A match: arm is an expression, not a block, but it is the same frame a conditional's block is (BT-3947, closing BT-3875): a match: whose arm assigns an outer local (x match: [#a -> (t := t + 1); _ -> 0]) is a local-threading producer wherever a conditional would be (a statement, an assignment's value, an operand, a loop body, a conditional or match: arm), in class, value-type and actor methods and in the REPL, and the write comes back. It stays a compile error where it is not a producer: a write in a guard (x when: [(t := 1) > 0] -> ...), or a match: that is the subject of another match:; bind the value there (t := x match: [#a -> t + 1; _ -> t]).

Position errors. A construct that writes an outer local is accepted as a statement wherever it sits. At any other position it is accepted only where a producer lowers it — a method-root operand site, a frame site, or a REPL site — and is otherwise rejected rather than allowed to drop the write:

error: `detect:ifNone:` writes outer local `t`, but as a statement inside a conditional arm in an actor method
       the write is not threaded back (BT-3913)

The rewrite is the same as for the §6 error: bind the construct's value to a local, or hoist it out of the nesting. What stays an error: a construct as a cascade part, a conditional's receiver, an interpolation or a match: subject (there is no statement boundary for the write to come back through); a statement inside a whileTrue:/whileFalse: condition block whose loop body is not a block literal; a detect:ifNone: with a stored search block; a ^ whose value is a loop or fold inside a plain closure in an actor method (^xs do: [...] inside a detect:ifNone: handler or sort block; class and value-type methods accept this shape); a value-bearing site in an actor fold body (the producer does not lower one, BT-3797); and a match: arm write where the match: is not a producer (a guard write, or a match: at no producer site). These are permanent restrictions, not gaps: the 733-shape oracle reports zero silent drops. A loop or fold that writes a local of its own conditional arm (c ifTrue: [m := 0. s := xs inject: 0 into: [:a :e | m := m + e. a + e]. ...]) is accepted as a statement or as the whole value of an assignment in that arm, when the conditional is at the method root of an actor or value-type method and is an ifTrue: / ifFalse: / ifNil: / ifNotNil: conditional in any of their keyword combinations (BT-4367). Limits of the lowering remain, none a designed restriction: in a class method the same shape is rejected (the class-method arm does not lower it, and compiles to wrong answers if let through); the loop at an operand or array-literal site of an arm is rejected (r := 1 + (xs inject: ...), #[(xs collect: ...)]); the arms of and: / or: and the handlers of a dictionary lookup (at:ifAbsent:, at:ifPresent:ifAbsent:) are rejected; and a conditional nested in a loop or a fold keeps its own rules. A conditional (ifTrue: … ifNil:ifNotNil:, and:, or:), on:do:, ensure: or match: nested in such an arm that writes one of the arm's locals threads the write back as a statement, as an assignment's value or as the arm's value, in actor and value-type methods (BT-4460, which also lets a loop inside it write the arm's locals); in a class method it does as a statement or the arm's value. Hoist the writing loop to a statement and capture the pure fold value to get a rewrite that works everywhere.

Assignments used as values. A local assignment whose value is used by the expression around it, rather than standing as its own statement, rebinds the local like any other assignment (BT-3910, ADR 0131 §1). That covers an operand (x := (t := t + 1) + 1), a collection-literal or interpolated element (#[t, (t := 7), t]), the value of another assignment or of ^ (x := t := 7, ^t := 7), and a message receiver, including a conditional's or a cascade's ((t := t + 1) > 0 ifTrue: [...]), in methods, in loop and fold bodies and in the REPL alike. The value of the assignment is the assigned value, and a sibling that is read before it sees the old value:

#[t, (t := 7), t]    // with t = 0: #[0, 7, 7]

^t := e returns e after rebinding t. Nothing runs after the return that could read t, so the write is dead and beamtalk lint warns (dead_returned_assignment) and suggests ^e.

An ensure: cleanup cannot read a local its protected block wrote if the block can exit early. When the protected block leaves by a ^ ([^t := t + 1] ensure: [t printString], and equally [t := t + 1. ^t] ensure: [t printString], a ^ in a block nested in it, or evaluating a block value that may hold one) or by an error raised after the write, the cleanup runs over the locals the protected block was entered with and would read the old t. A cleanup that reads a local the protected block writes is therefore a compile error whenever something after the write may exit that way: a ^, any message send (an arithmetic operator included), a destructuring assignment or match:, or the next iteration of a loop or fold body. This is a deliberate restriction (ADR 0133, Consequences), not a gap to be closed: lowering it would need a new runtime mechanism. The check over-approximates: anything after the write that may raise counts, even inside an on:do: (in the protected block) that catches it, so [[t := 9. 1 / 0] on: Error do: [:e | 0]] ensure: [log record: t] is rejected although the cleanup would see 9. A write that is the last thing the protected block does is seen. Assign the local after the ensure: (or compute its value outside the protected block), keep the ^ out of the protected block, or do not read the local in the cleanup:

// ❌ ERROR: if `self work` raises, the cleanup would see the old `count`
[count := count + 1. self work] ensure: [log record: count]

// ✅ Assign outside the protected block
count := count + 1
[self work] ensure: [log record: count]

// ✅ The write is the last thing the protected block does
result := nil
[result := self work] ensure: [log record: result]

An actor's fields are not affected: an ensure: cleanup reads them live.

A ^ in a stored closure answers what the closure captured. A block that is not run where it is written (stored in a local, passed to a method, ...) captures the values of the locals it reads when it is created. A ^ in such a block that reads a local the method assigns after the block is created, or inside the body of a loop or fold that creates it, may answer the old value, so it is rejected conservatively as a compile error (BT-4003); at the REPL, so is one that reads any workspace binding (a later input may assign it). The rule treats every such block as escaping (as ADR 0133 does for a block passed to a user method), so it also rejects a block that is in fact run before the assignment and would answer right: t := 0. self withFallback: [^t]. t := 5 is an error even if withFallback: runs the block at once. Pass the current value in as an argument ([:v | ^v] value: t) or write the block where it is run.

A ^ at the REPL ends the input. A REPL input is a method body: a ^ that runs in place, at the root of the input, in a conditional arm, in an evaluated or protected block (value, on:do:, ensure:), or in the body of a loop or collection operation (#(1, 2) do: [:x | ^x], [n < 3] whileTrue: [^10]), ends the input with its value, as it ends a method (BT-4288, BT-4312). The bindings written before the ^ keep their values, and the rest of the input does not run:

w := 0
#(1, 2, 3) do: [:x | w := w + x. x == 2 ifTrue: [^w]]   // => 3
w                                                        // => 3
3 timesRepeat: [^8]. w := 99                             // => 8 (w is still 3)
k := 1. ^7. k := 2                                       // => 7 (k is 1)
true ifTrue: [^3]. 5                                     // => 3

An ensure: cleanup that such a ^ runs on its way out keeps its writes, as in a method: w := 0, then [^5] ensure: [w := 9] answers 5 and leaves w at 9. The same holds for an actor's fields: a field an ensure: cleanup writes while a method's ^ unwinds is kept.

Such a ^ inside the value of a top-level assignment (r := true ifTrue: [^3], r := #(1, 2) do: [:x | ^x]) is a compile error: a method never assigns r, but the workspace would bind it to the input's value. Drop the ^ and assign the value (in a loop, answer it with detect:ifNone: or inject:into:), or leave the assignment out and let the ^ answer the input. The rule is deliberately conservative: it rejects such a ^ in every statement of the input, including a statement that is not the last of a multi-statement input (r := true ifTrue: [^3]. r), where the throw would already end the input before r is assigned and so give method semantics. It does not depend on where the statement sits in the input. A loop with a ^ in its body held in a block that is not run where it is written (b := [#(1, 2) do: [:x | ^x]], or such a block passed to a method) is a compile error too: the block may run in a later input, after the one that created it has ended, so nothing could catch the ^. A ^ in a stored closure outside any loop (b := [:x | ^x]) answers its value where it stands, as the closure's value.

Actor Blocks See Live State

In an actor instance method (ADR 0137) a block that reads or writes self.field, or sends to self, sees and changes the actor's current state, wherever the block is made and wherever it runs: a loop body, an on:do: or ensure: body, a block with a ^, a block stored in a field and run by a later message, or a block passed to one of the actor's own methods.

Actor subclass: Counter
  state: n = 0
  state: onTick = nil

  twice: aBlock =>
    aBlock value
    aBlock value

  addTwice =>
    self twice: [self.n := self.n + 1]
    self.n                      // 2

  arm => self.onTick := [self.n := self.n + 10]
  tick =>
    self.onTick value
    self.n                      // 10, then 20

A block at home (running in the actor's own process, inside one of its messages) reads and writes the live fields. A block that has been carried away to another process (handed to another actor, or run by a task) reads the fields as they were when the block was created; a write from there raises actor_state_unreachable, and a send to self from there is an ordinary message to the actor. on:do: restores the actor's fields to their values on entry to the protected block when it handles an error; ensure: cleanups see every write the protected block made before it ended; a ^ stores its writes before it leaves. Blocks that assign a captured local are still governed by ADR 0133's rule above.

One older rejection remains: the local-threading rows listed at the end of the Capturing Variables discussion. In an actor method, a loop or collection operation whose block sends to self or writes a field works as an operand anywhere: inside the body of another one (#(1, 2) do: [:x | x + (self.items inject: 0 into: [:b :y | b + self bump])] sends bump four times and answers each sum, BT-4287), and as the receiver of a conditional (((xs inject: 0 into: [...]) > 3) ifTrue: [...], and:, or:, ifNil:), a dictionary lookup's key, a cascade message's argument, or an argument of a super send, error:, fieldAt:put:, a block invocation ([:z | z] value: ...), a cast or a self-send that also takes a block literal (BT-4310; these were compile errors before). Field writes in stored closures of value-type methods stay a compile error. Those messages say so when they fire.

Why This Design?

Property✅ Benefit
UniversalLocal variable mutations work in every control-flow block — no whitelist; a block with no way back is a compile error, not a lost write
Smalltalk-likeNatural iteration patterns work; a user-defined HOM takes a block that answers a value (ADR 0133)
SafeIn value-type methods, field mutations in stored closures are caught at compile time; in actors they see live state (ADR 0137)
Good DXClear errors with fix suggestions
BEAM-idiomaticCompiles to tail recursion + state threading
PerformantStdlib hot paths are zero overhead (Tier 1); user HOMs ~65ns (Tier 2)

Error Messages

In a value-type method, a field assignment inside a stored closure is a compile error that suggests moving the mutation into a method of its own:

addToSum: item => self.sum := self.sum + item

The same assignment in an actor instance method compiles and writes the live field.


Actor Message Passing

Beamtalk uses sync-by-default actor message passing (ADR 0043). The . message send operator uses gen_server:call, which blocks the caller until the actor processes the message and returns a value. This is the same natural synchronous feel as Smalltalk, while preserving full process isolation and fault tolerance.

Default: Sync with Direct Return

// Load the Counter actor
Workspace load: "examples/counter.bt"

// Spawn an actor — returns a reference
c := Counter spawn

// Messages to actors return values directly
c increment             // => 1
c increment             // => 2
c getValue              // => 2

The method's return value is the reply. A sync method can instead defer its reply with self deferReply (OTP {noreply, State} + gen_server:reply/2) and answer the caller later; see Deferred Replies.

REPL and Compiled Code

Actor sends behave identically in REPL and compiled code — both return values directly:

> c := Counter spawn
Actor(Counter, _)

> c increment
1

> c increment
2

> c getValue
2

Explicit Async Cast (!)

For fire-and-forget scenarios, use the ! (bang) operator, which uses gen_server:cast and returns nil immediately:

// Fire-and-forget — does not block, returns nil
c increment!

The ! is postfix — it terminates the send it applies to. A cast is only legal as a bare statement: using its (always-nil) value in an assignment, return, or argument is a parse error (cast_in_expression_error).

Use ! when you intentionally don't need the result and don't want to block.

An error raised by a method sent with ! has no caller to go to, so it crashes the actor, as in OTP (ADR 0134): terminate: runs with the error as its reason, onExit: observers receive it, and a supervisor restarts the actor according to its policy. If a failure is expected and should not stop the actor, handle it inside the method with on:do:. A sync send (.) is unaffected: its error is returned to the caller and the actor carries on.

self foo! inside an actor's own method is a real cast to the actor's own mailbox: foo runs after the current message finishes, and its field writes are kept. It does not run inline, so the rest of the current method does not see its effects.

A send to a local bound to self (other := self. other setX: 7) works like a self-send on the live state (ADR 0137): it runs against the actor's current fields and its writes are kept, whether self got there by assignment, as an argument, via yourself, or out of a collection. It is an ordinary send, not a statically resolved self-send, so it pays the dispatch cost; prefer self directly where that matters.

How long an async send's future can stay pending

A future whose actor dies is rejected at once with #future_expired (BT-5020). While the actor stays alive the future has no deadline of its own, with one exception: an unsettled async-send future is rejected with #future_expired after one hour (BT-5084). This bound stops a future from being held open forever by an actor that never replies; an async send that takes longer than an hour is rejected even though its actor is still running. Raise it with the future_watcher_cap_ms application environment variable of beamtalk_runtime.

Deadlock Prevention

Because . sends block the caller (gen_server:call), two actors calling each other creates a deadlock. The default timeout is 5000ms, after which a #timeout error is raised:

// DeadlockA calls DeadlockB, which calls DeadlockA — timeout after 5s
self should: [a callPeer] raise: #timeout

Design actor interactions to avoid circular synchronous calls. Use ! (cast) when an actor needs to notify another without expecting a response.

Custom Timeouts

The default . send timeout is 5000ms. For actors that may take longer (database queries, HTTP calls), use withTimeout: to create a timeout proxy:

// Wrap an actor with a custom timeout (milliseconds)
slowDb := db withTimeout: 30000
slowDb query: sql              // forwarded with 30s timeout
slowDb stop                    // stop the proxy when done

// Infinite timeout (use with care — blocks indefinitely)
infDb := db withTimeout: #infinity
infDb query: sql
infDb stop

withTimeout: returns a TimeoutProxy — a lightweight actor that forwards ordinary messages to the target via doesNotUnderstand:args: using the specified timeout. Lifecycle messages such as stop apply to the proxy itself, not the target. This is pure message passing with no special syntax or reserved keywords.

Lifecycle: The proxy is a separate actor process. Capture the reference and call stop when finished to avoid leaking processes.

Static Typing of Actor Protocols (ADR 0104)

An Actor subclass:'s public method set is its message protocol — the checker types actor sends exactly as ordinary method sends, with no parallel channel type and no new syntax. Four typing rules apply (all advisory per ADR 0100, and static-only — no runtime, codegen, or wire change):

  1. A sync send types as the method's return. c increment on a Counter whose increment declares (or infers) -> Integer types as Integer, and forwards its declared/inferred return to callers:

    c := Counter spawn
    c increment          // :: Integer — the method's declared/inferred return
    
  2. A bare cast (!) types as Nil. The fire-and-forget gen_server:cast has no synchronous reply, so a cast statement evaluates to Nil regardless of the target method's return type. (Using a cast's value in an assignment, return, or argument is already a parse error — see Explicit Async Cast above). One consequence: a method declaring a non-Nil return whose body ends in a bare cast now warns "body returns Nil" — usually a genuine bug where a mutator returns nothing:

    c increment!         // :: Nil — no reply is awaited
    
    // ⚠️ Method 'bump' declares return type Integer, but body returns Nil
    bump -> Integer => c increment!
    
  3. spawnWith: keys are checked against state: slots. The keys of a literal init-state map are validated against the actor's declared state: slots; an unknown key is a Warning (a provably-failing construction, not merely an unresolved selector) with a typo suggestion naming the nearest slot. When a slot is typed, the literal value's type is checked against it too:

    Counter spawnWith: #{#count => 0}     // :: Counter — key `count` is a declared slot
    Counter spawnWith: #{#cuont => 0}     // ⚠️ unknown state key `cuont` — did you mean `count`?
    

    Only a literal map is inspected; a spawnWith: argument flowing in through a variable is not key-checked. The rule fires only for Actor subclass: receivers.

    Supplying a late slot by key counts as assigned. spawn's init/1 merges the declared defaults with the caller's map, caller winning, so CodexClient spawnWith: #{#proc => aFakeSubprocess} puts proc in the state map even though it is declared late — this is legitimate dependency injection (substituting a value for a slot normally acquired by a lifecycle call), not a violation of late's "absent until assigned" contract, and it also satisfies the Definite Assignment construction-site check the same way supplying any other unassigned slot does. See late Slots above.

  4. withTimeout: is transparent; cross-process DNU grades like a local send. withTimeout: returns a value typed as the wrapped actor (not the opaque TimeoutProxy), so forwarded calls resolve the wrapped class's real return types. A timeout raises rather than returning, so method return types are unchanged. An unknown selector on a statically-known actor gets the same knowledge-graded ADR 0100 diagnostic as a local send — the process boundary is invisible to the checker:

    (db withTimeout: 30000) query: sql    // resolves query:'s real return, not Dynamic
    
    logger := Logger spawn
    logger logg: "hi"                     // ⚠️ Logger does not understand 'logg:' — did you mean 'log:'?
    

See ADR 0104 for the full rationale, prior art, and the metaclass-aware constructor inference (ADR 0083) that types spawn / spawnWith:.

BEAM Mapping

BeamtalkBEAM
. send (sync)gen_server:call — blocks until reply
! send (async cast)gen_server:cast — returns immediately
Timeoutgen_server:call default 5000ms timeout
withTimeout:Proxy wrapping gen_server:call/3 with custom timeout

Caller-Process Class Method Dispatch

A class method runs in the caller's process unless its selector is process-bound (Class-Side Methods), so a long-running class method (batch processing, report generation) does not block other messages to the class, and no special send is needed. perform:withArguments: follows the same rule:

MyClass computeReport                              // runs in the caller
MyClass perform: #add:to: withArguments: #(3, 7)   // so does this

performLocally:withArguments: is removed (ADR 0153); use perform:withArguments:.

PersistentTerm: build-once computed constants (ADR 0153)

PersistentTerm is a sealed, class-side facade over Erlang's persistent_term, beside ProcessDictionary. It holds a value that is expensive to build and read many times, such as a lookup table. There is no at:put:.

Object subclass: HpackHuffman
  class tables -> Tuple =>
    PersistentTerm at: #hpack_huffman_tables ifAbsentPut: [self buildTables]
MethodAnswers
PersistentTerm at: key ifAbsentPut: blockThe stored value. On a miss it runs block, stores the result and answers it
PersistentTerm at: key ifAbsent: blockThe stored value, or the block's value. Stores nothing
PersistentTerm includesKey: keyWhether a value is stored (a stored nil counts)
PersistentTerm erase: keytrue if a value was removed. Forces a global GC

Rules:

Passing Blocks Through Class Methods

See also: class-method-process-resource flags process-tied resources created in a class method that runs in the caller (see Class-Side Methods).

Class methods run in the caller, and so do their blocks (ADR 0142, ADR 0153). A class has no state of its own, so unless the selector is process-bound the class method runs in the caller's process, however it is reached: statically, through a variable, perform:, Beamtalk classNamed:, or a class passed as an argument. A block passed into it runs where it was written (inside an actor, that is at home in the ADR 0137 sense), self() and the process dictionary are the caller's, links, monitors, timers and FFI resources it creates belong to the caller, there is no class_send timeout, an exit inside the method exits the caller, and messaging the same class from inside does not raise dispatch_error. Calls are not serialised through the class process: two callers run the method at once. self is still the class object (the real class reference, even for an inherited method), so self new, self new:, self spawn, self spawnWith:, self class and class-side self-sends behave as in any other class method (BT-4029). This matters most when building a Collection subclass: implementing do: by delegating to a class-side helper works, and so does a helper that reaches back into its own class.

Object subclass: Driver
  class run: aBlock over: aList -> Nil =>
    aList do: [:x | aBlock value: x]    // aBlock runs in the caller
    nil

Collection subclass: Batch
  field: items :: List = #()
  size -> Integer => self.items size

  do: block :: Block -> Nil =>
    Driver run: block over: self.items
    nil

When there is a hop. Only a process-bound selector (new, new:, spawn, startLink, ...) runs in the class object's gen_server process; a class method installed as a runtime fun runs in the caller like any other. A block passed into such a method runs there too, not where it was written (BT-3022). Arguments and return values cross that boundary as copies, so blocks that compute answers work normally. Two things do not survive the hop:

Non-local return (^) does cross the boundary: the signal is relayed back and unwinds the enclosing method as it would without the hop.

For state shared between callers, use an Actor, AtomicCounter, Ets or PersistentTerm; see A class has no state.

Hot-patching and direct calls. A literal send of a class method the class itself defines compiles to a guarded direct call: it reads one persistent_term key for that call target, holding the class reference the method receives, which the runtime installs only while the class's direct-call flag holds (beamtalk_class_shadow_flags:direct_call_ok/2, which a runtime class-method fun on the class turns off: the fun, not the compiled method, answers), a dynamic send would run that same compiled method in the caller, the method is still exported and the class process is alive; otherwise it falls back to the ordinary class send, which answers what a dynamic send answers. An inherited method sent to a literal receiver takes the dynamic path, which also runs in the caller, so no call site names a superclass module. Reloading a class, re-parenting it, removeSelector:, a runtime class-method fun or the class process going down all erase the flag and those keys, so code compiled earlier follows the change without being recompiled. A reload erases them while the old code is still current, so a static send of a method the reload dropped answers what a dynamic send answers, never undef. The key also names the class, so after renameTo: (or when a removed class's module name is reused) a call site that still names the old class does not reach the new one. A descendant's flag is erased just after an ancestor's change is written, so for a moment a descendant's static send can still run in the caller: the same window a reload has for its own new code.

The new/new: direct-construction verdicts of Value classes are still baked into each compiled module. If a class gains a class-side new:, the runtime logs a warning naming every subclass that still builds new: directly and so bypasses the new override (BT-4126). Recompile the code the warning names. A release upgrade recompiles everything, so this only affects targeted hot-patches.

Errors.

Error kindRaised when
abi_mismatchThe loader refuses a compiled class module built for a different runtime ABI (every module compiled before ADR 0153 included): recompile. See below.

Class-module ABI. Every compiled class module records the runtime ABI it was built for as module_abi (currently 4) in __beamtalk_meta/0. The loader (class registration, hot reload, and the release upgrade preflight) refuses a module whose module_abi is missing or differs from the running runtime's, with a structured abi_mismatch error that names the module and says to recompile. Every module compiled before ADR 0153 declares no module_abi (it declared class_var_abi instead) and is refused this way, not with an undef from a deleted runtime module. This gate is the backstop behind the build stamp: a normal build is invalidated when BEAMTALK_VERSION changes, so a stale BEAM rarely reaches it. Hot upgrades across a release that changed the ABI are not supported: restart the node and recompile every package.

Actor-to-Actor Coordination

Because . sends are synchronous, when an actor method calls another actor internally, the caller waits for the nested call to complete before continuing. The sync barrier pattern (explicit round-trip queries) is generally no longer needed:

// With sync-by-default: bus notify: calls receive: on each subscriber
// synchronously. When notify: returns, all subscribers have processed it.
bus notify: "hello".
col eventCount          // => 1 (already processed)

The sync barrier pattern is only needed when using ! (cast) sends internally:

// If bus uses `!` internally to forward to subscriber:
bus notify: "hello".    // bus sends subscriber ! receive: "hello" internally
col events.             // barrier: ensures col processed the cast message
col eventCount          // => 1 (now correctly reflects the event)

Server — OTP Interop (ADR 0065)

Server is an abstract subclass of Actor for BEAM-level OTP interop. The class hierarchy expresses the abstraction boundary:

Object
  └── Actor           # Beamtalk objects — messages, state, Timer
        └── Server    # BEAM processes — handleInfo:, raw OTP interop (abstract)

Defining a Server

Use Server subclass: when you need to receive raw Erlang messages (timer events, monitor DOWN tuples, system messages). All existing Actor methods continue to work — Server inherits everything from Actor.

Server subclass: PeriodicWorker
  state: count = 0

  initialize =>
    Timer send: #tick to: self after: 1000

  handleInfo: msg =>
    msg match: [
      #tick -> self tick;
      _ -> nil
    ]

  tick =>
    self.count := self.count + 1
    Timer send: #tick to: self after: 1000

  getValue => self.count

Timer send:to:after: delivers the message to the server's mailbox exactly as erlang:send/2 would, so it arrives in handleInfo: (see § Message Timers).

A match: arm body is an expression, so an arm that needs more than one statement calls a method (#tick -> self tick). Do not write #tick -> [ ... ]: that arm answers the block itself without running it (a block that writes a field or sends to self fails to compile; see § Match Expression).

handleInfo: Semantics

onLinkedExit:reason: Semantics

By default a Server that traps exits (see Actor>>terminate:) treats a linked process's EXIT like an untrapped link would: a non-#normal reason stops the server with that reason, and #normal is ignored. A server that links worker processes on purpose (for example Erlang erlang spawn_link:) can handle their exits itself by overriding onLinkedExit: source reason: reason:

Migration: Actor to Server

Promoting an Actor to a Server is a one-word change. All existing methods continue to work:

// Before
Actor subclass: MyThing
  // ...

// After — all existing methods still work, handleInfo: now available
Server subclass: MyThing
  handleInfo: msg => ...

Timer Lifecycle

Timer processes (Timer every:do: and Timer after:do:) are linked to the calling process via spawn_link. This means:

Actor subclass: Ticker
  state: count = 0

  initialize =>
    Timer every: 1000 do: [self tick!]   // async cast: the block runs away, so it messages the actor

  tick => self.count := self.count + 1
  getValue => self.count

A timer block runs in the timer's process, away from the actor (ADR 0137): a field read there sees the value from when the block was made, a field write raises actor_state_unreachable, and a self-send is an ordinary message to the actor. Prefer the ! cast: a synchronous self tick from the timer works, but it blocks the timer until the actor answers, and it deadlocks if the actor is ever waiting on that timer.

No state: for the timer reference, no terminate: cleanup needed — the link handles it.

Message Timers

A block timer runs its block in a separate process, so the block cannot touch the actor's state; it can only send the actor a message. When the actor is a Server, deliver the message directly with a message timer instead, and handle it in handleInfo::

t := Timer send: #tick to: self after: 1000          // one-shot; answers a Timer
t := Timer send: {#readTimeout, tag} to: self after: (Duration seconds: 5)
t := Timer send: #tick to: self every: 1000          // repeating
t cancel                                             // => Boolean
t isActive                                           // => Boolean
Server subclass: Poller
  state: timer = nil

  initialize => self.timer := Timer send: #poll to: self every: 5000

  handleInfo: msg =>
    msg match: [
      #poll -> self poll;
      _ -> nil
    ]

  poll => nil

  pause => self.timer cancel

Continuations (continueWith:)

self continueWith: #selector (or self continueWith: #sel: withArguments: #(arg)) asks the actor to run a follow-up step after the current message has been handled and before any other message in its mailbox. It is OTP's {noreply, State, {continue, Term}} / handle_continue/2. Neither alternative gives this ordering: self foo is a direct call that runs immediately, and self pid send: #foo (a raw message for handleInfo:) queues behind everything already in the mailbox.

Server subclass: Connection
  state: sock = nil

  handleInfo: msg =>
    msg match: [
      {#ready, s} -> self onReady: s;
      _ -> nil
    ]

  onReady: s =>
    self.sock := s
    self continueWith: #handleConnection   // runs before any queued #tcp message

  // Set up the socket here, before the first #tcp message is handled.
  handleConnection => self.sock

Both methods are defined on Actor and answer #ok.

Deferred Replies (deferReply)

self deferReply takes the reply token of the sync call being handled and returns a ReplyTo. The method returns without answering: the caller stays blocked until the token is answered with reply: or replyError:, from any later method of the same actor (handleInfo:, another sync method, a continueWith: step). It is OTP's {noreply, State} with the From kept for gen_server:reply/2, and it is how a Server implements a blocking read or a flow-control wait without a receive.

Server subclass: Connection
  state: waiting :: Dictionary(Integer, ReplyTo) = #{}

  readData: streamId :: Integer -> Binary =>
    self.waiting := self.waiting at: streamId put: self deferReply
    nil   // ignored: the caller is answered later

  onDataFrame: streamId :: Integer data: data :: Binary =>
    (self.waiting at: streamId) reply: data
    self.waiting := self.waiting removeKey: streamId

BEAM Mapping

BeamtalkBEAM
Server subclass:gen_server with handle_info/2 dispatch
self deferReply / replyTo reply:{noreply, State} / gen_server:reply(From, _)
handleInfo: msghandle_info(Msg, State) callback
self continueWith: #sel{noreply, State, {continue, _}} + handle_continue/2
Actor subclass:gen_server with handle_info/2 ignore stub
Timer spawn_linkTimer process linked to calling process

Supervision Trees (ADR 0059)

Beamtalk provides declarative OTP supervision trees via Supervisor subclass: and DynamicSupervisor subclass:. This is the Beamtalk idiom for "let it crash" fault tolerance — define which actors should be restarted automatically, and how.

Static Supervisor

Subclass Supervisor and override childSpecs to return a list of actor classes (or SupervisionSpec values for per-child configuration). The supervisor starts all children at startup using OTP one_for_one strategy by default.

Important: supervisor configuration (childSpecs, strategy, maxRestarts, restartWindow; childClass, maxChildren, childShutdown on DynamicSupervisor) is instance-side (ADR 0135). The runtime sends each setting to the supervisor being started, from inside its own OTP init/1: self is that supervisor and self args its start args. Reading self args and passing self as a value are fine; sending a message to self (self count, self which: X) fails the start with #supervisor_start_failed and a hint, because the supervisor is still starting. See Instance configuration and start args.

Supervisor subclass: WebApp
  childSpecs => #(DatabasePool HTTPRouter MetricsCollector)

Start the supervisor with supervise. It registers under its class name so it can be found from anywhere. supervise and terminate: both return Result values (ADR 0080) — use unwrap at boot / in the REPL, or ifOk:ifError: / andThen: for recoverable flows:

// Boot-style: crash on failure (application boot, test setup, REPL exploration)
app := (WebApp supervise) unwrap
// => Supervisor(WebApp, _)

// Idempotent — second call also returns a successful Result wrapping the
// already-running supervisor, without restarting
(WebApp supervise) isOk
// => true

// Recoverable form — branch on the Result explicitly
(WebApp supervise)
  ifOk:    [:sup | sup count]
  ifError: [:e | Logger error: e message]

// Find the running instance by class name (no reference needed — returns the
// bare supervisor or nil, unchanged from pre-ADR-0080 semantics)
WebApp current
// => Supervisor(WebApp, _)

Inspect and manage children:

app count                                 // => 3  (number of running children)
app children                              // => the 3 running child objects, in declaration order
(app which: DatabasePool) unwrap           // => Actor(DatabasePool, _)  (running child instance)
(app terminate: HTTPRouter) unwrap        // gracefully stop a single child; Result(Nil, Error)
app stop                                  // stop the supervisor and all children (unchanged — Nil)

// After stop:
WebApp current                            // => nil

terminate: is idempotent — terminating a child that is already gone returns Result ok: nil, not an error (see idempotent-startup convention below).

which: and terminate: find a child by its class, including one declared withId:. When several children share the class, both return Result error: with kind #ambiguous_child (and terminate: terminates nothing); use the by-id API below then.

By id (BT-3966). Every child spec has an OTP id: the class name by default, or the withId: value (a Symbol or an Integer). These methods work on any supervisor instance — the supervise singleton, a spawn/spawnWith: instance, or a nested supervisor reached through childWithId: or children:

Supervisor subclass: ServerSupervisor
  strategy => #restForOne
  childSpecs => #(
    (Listener supervisionSpec withId: #listener withRestart: #permanent),
    (AcceptorPoolSupervisor supervisionSpec withId: #acceptorPool withRestart: #permanent))

server := ServerSupervisor spawn
server whichChildren collect: [:c | c id]       // => #(#listener, #acceptorPool)
listener := (server childWithId: #listener) unwrap
(server terminateChild: #acceptorPool) unwrap   // suspend
(server restartChild: #acceptorPool) unwrap     // resume => the new AcceptorPoolSupervisor
(server terminateChild: #acceptorPool) unwrap
(server deleteChild: #acceptorPool) unwrap      // drop the spec for good
MethodReturnsErrors
childrenList(Object): the running children, in declaration orderraises #stale_handle
whichChildrenList(SupervisorChild): one per spec, in declaration order, incl. restarting/stoppedraises #stale_handle
childWithId: idResult: the running child, or ok: nil if the spec's child is restarting/stopped#child_not_found, #type_error, #stale_handle
terminateChild: idResult ok: nil; idempotent for an unknown or already-gone id#terminate_failed, #type_error, #stale_handle
restartChild: idResult: the newly started child#child_not_found, #child_running, #child_start_failed, #type_error, #stale_handle
deleteChild: idResult ok: nil#child_not_found, #child_running, #type_error, #stale_handle

A SupervisorChild is a value with id, child (nil unless running), status (#running, #restarting or #stopped), type (#worker or #supervisor) and childClass (nil for a non-Beamtalk module), plus isRunning and isSupervisor.

restartChild: needs a #permanent or #transient child. The default restart policy is #temporary, and OTP removes a temporary child's spec as soon as it terminates, so restartChild: on it returns #child_not_found (and terminateChild: on it again returns ok: nil). Declare withRestart: #permanent on children you suspend and resume.

Breaking (BT-3966): Supervisor>>children used to return the child ids as Symbols. It now returns the running child objects, the same as DynamicSupervisor>>children; use whichChildren collect: [:c | c id] for the ids.

DynamicSupervisor has children -> List(C): its live children (restarting ones left out, order unspecified). It copies the whole child list out of the supervisor in one message, O(n) in the number of children, so use it for bulk operations (drain, broadcast) and startChild:name: + ChildClass named: to find one child. simple_one_for_one children have no ids, so DynamicSupervisor has no whichChildren/childWithId:/restartChild:/deleteChild:; its terminateChild: takes the child object.

Configuration Defaults

Override these instance methods in your subclass to customise restart behaviour:

MethodDefaultDescription
childSpecs(required)The children of a static Supervisor
strategy#oneForOneOTP restart strategy (#oneForOne, #oneForAll, #restForOne)
maxRestarts10Max restarts before supervisor gives up
restartWindow60Time window (seconds) for maxRestarts
childClass(required)The child class of a DynamicSupervisor
maxChildren#infinityDynamicSupervisor child limit
childShutdownnilDynamicSupervisor child shutdown timeout
initializeno-opHook run once after a top-level start, in the caller
args—The start args (nil for supervise); not overridden
Supervisor subclass: CriticalApp
  childSpecs => #(Database Cache)
  strategy => #oneForAll       // restart all if any child crashes
  maxRestarts => 3             // give up after 3 crashes in 60 seconds

Instance configuration and start args (ADR 0135)

Configuration is a property of a running supervisor, so it lives on the instance side and is read from the supervisor being started, inside its OTP init/1. self is that supervisor's handle and self args its start args, so the same class can be configured differently per instance. supervise starts with nil args; a supervisor started as a DynamicSupervisor child with startChild: args gets args. OTP restarts replay the same args, so a restarted supervisor recomputes the same configuration. sup args also works from outside (it raises #stale_handle for a stopped supervisor).

DynamicSupervisor(Handler) subclass: ConnectionSupervisor
  childClass => self args at: #handler
  maxChildren => self args at: #numConnections
  childShutdown => self args at: #shutdownTimeout

DynamicSupervisor(ConnectionSupervisor) subclass: ServerPools
  childClass => ConnectionSupervisor

pools := ServerPools supervise unwrap
small := (pools startChild: #{#handler => Echo, #numConnections => 10, #shutdownTimeout => 5000}) unwrap
small maxChildren        // => 10
(small args at: #handler) // => Echo

Rules for configuration methods:

The post-start hook is the instance-side initialize (it was class initialize: sup). It runs once per top-level start, in the caller's process after the supervisor has started, so self is the supervisor and messages to it work. If it raises, the supervisor is stopped and the start fails: spawn and spawnWith: re-raise the error, while supervise, spawnAs: and spawnWith:as: answer Result error: with kind #supervisor_start_failed (as Actor spawnAs: does). Concurrent supervise calls on one class are served in arrival order; one that waits too long behind a start that does not finish also answers #supervisor_start_failed. Only class supervisionPolicy stays class-side. The old class-side forms (class children, class strategy, …, class initialize:) are compile errors with a fix-it: drop class, rename class children to childSpecs, and use self for sup in initialize.

For Erlang/Elixir developers. Every OTP concept has a direct counterpart (rows marked † arrive with BT-3966):

OTP / ElixirBeamtalk
supervisor:start_link(Mod, Args)MySup spawnWith: args (spawn passes nil)
supervisor:start_link({local, N}, Mod, Args)MySup spawnWith: args as: #n
whereis(N)MySup named: #n
Mod:init(Args)the configuration methods, reading self args
{ok, {#{strategy, intensity, period}, Children}}strategy, maxRestarts, restartWindow, childSpecs
self() inside init/1self inside those methods
child spec map; Elixir {Mod, Arg}Mod supervisionSpec withId: … withArgs: …
simple_one_for_one + templateDynamicSupervisor + childClass
Elixir max_children; child shutdownmaxChildren; childShutdown, withShutdown:
which_children, terminate_child, restart_child, delete_childwhichChildren, terminateChild:, restartChild:, deleteChild: †
"never call yourself from init"the same rule; OTP's calling_self becomes #supervisor_start_failed with a hint

Three deliberate differences:

  1. init/1 is split into one method per setting, so a subclass overrides strategy alone and inherits the rest. Each method is a separate send, so expensive work belongs in childSpecs only, not repeated in several settings.
  2. supervise (idempotent "ensure it is running") has no OTP counterpart; it serves REPL re-evaluation and the [application] boot path.
  3. initialize runs after start in the caller, where an Erlang programmer would put code after start_link returns.

Instances and arguments (ADR 0135)

supervise ensures, spawn creates. supervise makes sure the one class-named instance is running (registered under the class's module, found by current, idempotent). The spawn family makes a new instance per call, so one class can run any number of trees — one per server, per tenant, per test:

Message (class side)RegistrationReturns
supervisethe class name, idempotentResult(Self, Error)
spawn / spawnWith: argsnone (anonymous)Self; raises #supervisor_start_failed
spawnAs: name / spawnWith: args as: namenameResult(Self, Error); a taken name is #name_registered
named: namelookup + class checkResult(Self, Error): #name_not_registered, #wrong_class, #type_error
currentlookup by class nameSelf or nil (the supervise instance only)
a := AcceptorSupervisor spawnWith: cfg1
b := AcceptorSupervisor spawnWith: cfg2
a == b                                    // => false
AcceptorSupervisor current                // => nil   (spawned instances are not "current")
(a args at: #port)                        // => cfg1's port
a stop                                    // b keeps running

http := (ServerSupervisor spawnWith: cfg as: #http_server) unwrap
(ServerSupervisor named: #http_server) unwrap == http   // => true

Names are atoms: take them from a bounded, statically known set (ADR 0079), never from runtime data.

Nesting with supervisionSpec. A supervisor class answers supervisionSpec like an actor class: type #supervisor, shutdown #infinity, restart from class supervisionPolicy (default #permanent). withId:, withArgs: (the child's self args), withRestart:, withShutdown: and withName: (registers the child under a bounded name) apply; withClassMethod: and scope: #global fail the parent's start with a #type_error. Child ids may be Symbols or Integers, which suit generated pools and mint no atoms:

Supervisor subclass: AcceptorPoolSupervisor
  childSpecs =>
    ((1 to: (self args at: #numAcceptors)) collect: [:i |
      AcceptorSupervisor supervisionSpec withId: i withArgs: #{#id => i, #parent => self}]) asList

pool := AcceptorPoolSupervisor spawnWith: #{#numAcceptors => 3}
pool count       // => 3
pool children    // => #(1, 2, 3)

A bare supervisor class in childSpecs means X supervisionSpec, so it is an anonymous child: two parents that nest the same bare class run side by side, and InnerSup current does not find a nested instance (use parent which: InnerSup). A DynamicSupervisor whose child class is a supervisor starts a new anonymous child per startChild / startChild: args, and startChild: args name: n registers it.

The parent handle and the hang rule. Passing self in a child's args (#parent => self above) is how a child reaches its parent; replaying it on restart is safe because a child never outlives its parent. Never synchronously call a supervisor from code it is waiting on: its configuration methods and those of its nested supervisor children (a call to an ancestor there hangs; a call to self fails fast), and the initialize of any actor child (a call back stalls 5 s, then fails the start with a hint naming this rule). The same goes for a call from that initialize to whoever is starting the supervisor or calling startChild: (an owner actor that passed #owner => self), which is blocked in that start too. This holds during the initial start, every OTP restart and every DynamicSupervisor startChild:. A continuation the child requests in initialize (self continueWith:) runs after its start has returned, so that is the place for a child's first call to its parent.

A child's initialize completes before its start returns. Every supervised actor child starts like spawnWith:: the supervisor waits for the child's initialize before starting the next child (children start in order, as in OTP) and before its own start returns. An initialize that raises fails the start: spawn raises, and supervise/spawnAs: answer Result error:, with kind #supervisor_start_failed and the child's error in the hint (for startChild, #child_start_failed), instead of the child crash-looping after the start reported success. This is OTP's init/1 returning {stop, Reason}. On an OTP restart a failing initialize fails that restart, which counts against maxRestarts. A slow initialize delays the whole tree's start, and one that takes over 5 s fails it, so put slow or parent-dependent setup in a continueWith: step:

Actor subclass: Listener
  state: port = 0
  state: parent = nil

  initialize =>
    self bind: self.port          // a raise here fails the supervisor's start
    self continueWith: #register  // runs after the start has returned

  register => self.parent count   // safe: the parent is no longer waiting

Actor Supervision Policy

Each actor class declares its OTP restart policy via class supervisionPolicy:

Actor subclass: DatabasePool
  class supervisionPolicy => #permanent   // always restart on crash

Actor subclass: RequestHandler
  class supervisionPolicy => #transient   // restart only on abnormal exit

Actor subclass: BackgroundJob
  class supervisionPolicy => #temporary   // never restart (default)

SupervisionSpec — Per-Child Overrides

Use SupervisionSpec when you need to override a child's restart policy, provide startup arguments, or set a custom shutdown timeout:

Supervisor subclass: WebApp
  childSpecs =>
    #(DatabasePool
      HTTPRouter supervisionSpec withRestart: #transient
      (MetricsCollector supervisionSpec withId: #metrics withArgs: #{#port => 9090}))

Use withShutdown: to set how long a child gets to stop when its supervisor shuts it down — for children that need time to drain connections or flush state. The value is a ShutdownTimeout: an Integer (milliseconds, at most 4294967295), #infinity (wait as long as it takes) or #brutalKill (kill at once; terminate: does not run). The default is 5000ms for workers and #infinity for nested supervisors. On shutdown the supervisor sends the child exit(Pid, shutdown); a child that has not exited within the timeout is killed, and onExit: observers see the reason #killed. Only an actor that overrides terminate: traps exits, so only such an actor uses the time — any other actor exits as soon as it is told to. stop waits for the shutdown to finish, so a long timeout (or #infinity) can block the caller of stop that long. Any other value makes supervise return Result error: with kind #supervisor_start_failed.

HttpServer supervisionSpec withShutdown: 30000        // 30s graceful shutdown
SessionCache supervisionSpec withShutdown: #brutalKill // no cleanup needed

Use withName: (and the withName:withRestart: / withName:withArgs: / withName:withRestart:withArgs: combinators) to have the supervisor register the child atomically under a Symbol name on each restart. Named specs emit a #spawnAs: / #spawnWith:as: startFn so re-registration happens in the same OTP call that starts the process — held Actor named: references survive restarts (see ADR 0079 and the Actor Named Registration section below). name and classMethod cannot be combined on the same spec.

Supervisor subclass: WebApp
  childSpecs =>
    #((Counter supervisionSpec withName: #counter withRestart: #permanent))

Dynamic Supervisor

Subclass DynamicSupervisor to manage pools of actors started at runtime. Override childClass to declare which actor class the pool manages.

DynamicSupervisor(Worker) subclass: WorkerPool
  childClass => Worker
pool := (WorkerPool supervise) unwrap
// => DynamicSupervisor(WorkerPool, _)

// Start children dynamically — startChild returns Result(C, Error) where C is
// the DynamicSupervisor's child class parameter (Worker here)
w1 := pool startChild unwrap        // => Actor(Worker, _)
w2 := pool startChild unwrap        // => Actor(Worker, _)
pool count                          // => 2

// Start a child with custom init args — args is passed to the child's init/1
// the same way ActorClass spawnWith: args would
w3 := (pool startChild: #{#label => "y"}) unwrap   // => Actor(Worker, _)

// Recoverable variant — useful when a failing init should not abort the caller
pool startChild
  ifOk:    [:w | w process: 21]
  ifError: [:e | Logger warning: e message]
pool count                          // => 4

// Terminate a specific child — idempotent (Ok(nil) even if already gone)
(pool terminateChild: w1) unwrap    // => nil
pool count                          // => 3

// Stop the whole pool (unchanged — Nil, let-it-crash teardown)
pool stop
WorkerPool current                  // => nil

Capping the pool with maxChildren. Override maxChildren (default #infinity) to bound the number of live children — the Beamtalk equivalent of Elixir DynamicSupervisor's max_children. Once the pool holds that many children (count, plus any child whose automatic restart is pending), startChild, startChild: and startChild:name: return Result error: with kind #max_children (the error's details carry the limit) instead of starting a child; terminating a child frees a slot. Automatic restarts of existing children are never refused. The value must be a non-negative Integer or #infinity — anything else makes supervise return Result error: with kind #supervisor_start_failed (or, for a pool nested under a static Supervisor, fails the parent's start) — and is read from the instance each time the supervisor (re)starts, so it may depend on self args.

DynamicSupervisor(Worker) subclass: ConnectionPool
  childClass => Worker
  maxChildren -> Integer => 2

pool := (ConnectionPool supervise) unwrap
w := pool startChild unwrap        // => Actor(Worker, _)
pool startChild unwrap             // => Actor(Worker, _)
pool startChild error kind         // => #max_children
(pool terminateChild: w) unwrap    // => nil
pool startChild isOk               // => true

The limit is checked by the calling process just before the start, so it is exact when a single process starts children (e.g. one acceptor per pool) — concurrent starters racing past the check can briefly overshoot it by up to the number of racers.

Graceful child shutdown with childShutdown. Override childShutdown to set how long each child gets to stop when the pool is stopped (by stop, or by a parent supervisor) — a pool-wide analogue of the shutdown: option Elixir DynamicSupervisor takes per child. It takes the same ShutdownTimeout values as SupervisionSpec withShutdown: (an Integer in milliseconds, #infinity or #brutalKill). The default, nil, keeps the child class's own supervisionSpec value: 5000ms (the OTP default) for an actor, or #infinity for a supervisor. A child that overrides terminate: gets the full time to finish; one that overruns is killed (onExit: reason #killed). All children are told to stop at once and share one deadline. Keep #infinity for a supervisor child class: a finite value can kill it while it is still stopping its own children (the runtime logs a warning). The value applies to every child of the pool — OTP's simple_one_for_one keeps a single child spec for all dynamic children, so there is no per-startChild: override; the value is per pool instance, so compute it from self args (or use a separate pool class) for children that need a different timeout. An invalid value makes supervise return Result error: with kind #supervisor_start_failed.

DynamicSupervisor(Connection) subclass: ConnectionPool
  childClass => Connection
  childShutdown -> Integer => 15000   // let in-flight requests finish

Automatic restart replays per-child args. OTP tracks the exact args each dynamically-started child was started with. A child started via startChild: args that later crashes under a #permanent or #transient restart policy comes back with those same args, not blank defaults. A child started via the no-arg startChild restarts the same way. Restart re-runs init/1 from scratch — it does not resume the child's prior runtime state.

Named dynamic children — identity that survives restart. startChild: alone gives you a pid, and a simple_one_for_one-restarted child comes back as a different, unlabelled pid — there is no which:/children method on DynamicSupervisor to rediscover it (see below). startChild: args name: aSymbol closes that gap by combining args-replay with named actor registration: the child starts under {local, aSymbol} registration, and because OTP replays each dynamic child's own start args (including the name) on automatic restart, a crashed named child re-registers under the same name every time.

DynamicSupervisor(Monitor) subclass: CheckRegistry
  childClass => Monitor

pool := (CheckRegistry supervise) unwrap
m := (pool startChild: #{#check => "db"} name: #dbCheck) unwrap
// => Actor(Monitor, _)

// ... time passes; #dbCheck's process crashes and OTP restarts it ...

current := (Monitor named: #dbCheck) unwrap   // re-resolves to the NEW pid
current isAlive                                // => true

aSymbol should come from a bounded, statically-known namespace (e.g. a fixed set of configured checks/workers) — the same atom-exhaustion guidance that applies to Actor>>spawnAs: applies here, since names are Erlang atoms.

Why no which: id / children method on DynamicSupervisor. Static Supervisor>>which: and >>children (below) work because OTP's plain one_for_one gives every statically-declared child a stable childspec id. DynamicSupervisor's simple_one_for_one children are anonymous — matched only by pid — and supervisor:which_children/1 is a documented performance cliff at scale (it copies the whole child list out of the supervisor process in one message). startChild:name: + Actor named: gives "find this dynamic child again by a stable identity, surviving restart" without either limitation: a whereis/1-backed point lookup, not a full-list scan. This differs from DynamicSupervisor>>count, which only reports an aggregate number with no per-child identity at all.

Nested Supervisors

Supervisors can be nested — include another supervisor class in childSpecs:

Supervisor subclass: AppRoot
  childSpecs => #(DatabaseSupervisor WebTierSupervisor MetricsSupervisor)

A nested supervisor class goes through its supervisionSpec like any child (type #supervisor, shutdown #infinity, restart #permanent by default), so it is an anonymous child linked into the tree; use X supervisionSpec withId: … withArgs: … to give it an id or start args, and nest several of one class (see Instances and arguments). The outer supervisor shuts down inner supervisors (and all their children) gracefully on stop.

root := (AppRoot supervise) unwrap
root count                          // => 3
(root which: DatabaseSupervisor) unwrap  // => Supervisor(DatabaseSupervisor, _)

Lifecycle API returns Result (ADR 0080)

Supervisor lifecycle methods that can fail at a startup / registry boundary return a Result:

MethodSignatureError kinds
Supervisor class>>supervise-> Result(Self, Error)#supervisor_start_failed, #stale_handle
Supervisor class>>spawnAs: n / spawnWith: args as: n (both bases)-> Result(Self, Error)#name_registered, #reserved_name, #type_error, #supervisor_start_failed
Supervisor class>>named: n (both bases)-> Result(Self, Error)#name_not_registered, #wrong_class, #type_error
Supervisor>>terminate: aClass-> Result(Nil, Error)#terminate_failed, #stale_handle
Supervisor>>which: aClass-> Result(Object, Error)#stale_handle
DynamicSupervisor class>>supervise-> Result(Self, Error)#supervisor_start_failed, #stale_handle
DynamicSupervisor>>startChild / startChild: args-> Result(C, Error)#child_start_failed, #max_children, #stale_handle
DynamicSupervisor>>startChild: args name: aSymbol-> Result(C, Error)#child_start_failed, #max_children, #name_registered, #reserved_name, #stale_handle
DynamicSupervisor>>terminateChild: child-> Result(Nil, Error)#terminate_failed, #stale_handle

stop, current, children, and count are unchanged — they are teardown / lookup / inspection operations over an already-valid handle and follow let-it-crash semantics (teardown) or nil-on-miss (lookup), matching the rules established in ADR 0079 for the parallel Actor surface.

This mirrors Actor spawnAs: / Class named: from the Actor Named Registration section — both APIs speak Result at registry / lifecycle boundaries so call sites that chain actor spawns and supervisor operations stay on a single error idiom.

Errors carry structured beamtalk_error values (ADR 0015) with a Symbol kind and a human-readable message. REPL display shows them as Result error: (beamtalk_error <kind>) so they are greppable in logs and aggregatable in metrics.

Idempotent-startup convention

Across every supervisor lifecycle method, an operation returns a successful Result when the caller's target end state is already in effect, regardless of whether this call or a prior one established it. The rule is "does the target state hold now?" — not "did this call change the input?"

MethodTarget stateIdempotent case
supervise"this supervisor is running"OTP {already_started, Pid} → Result ok: sup
startChild / startChild:"a child of the configured class is running"fresh start → Result ok: child
terminate: / terminateChild:"this child is not running"OTP {error, not_found} → Result ok: nil

This matters in practice: you can call WebApp supervise at every entry point of your application without branching on "is this the first call?" — the second caller gets the already-running supervisor back in the ok branch. Similarly, a cleanup path that calls app terminate: StaleChild succeeds whether the child was still alive or already gone, so you never have to swallow a raise to express "stop it if it's running."

Error is reserved for outcomes the caller cannot trivially ignore:

isAlive and stop are sealed on Supervisor and DynamicSupervisor: the runtime answers them on a handle without a method lookup, so overriding either is a compile error. isAlive on a remote supervisor asks its node, as it does for an actor, and raises #node_down (as above, reason #noconnection or #timeout) when that node cannot answer.

Call-site patterns

Boot-style: crash on failure. Use unwrap at application boot, test setup, and in the REPL — the resulting exception carries the structured error payload.

app  := (WebApp supervise) unwrap
pool := (WorkerPool supervise) unwrap
w    := pool startChild unwrap

Recoverable: branch on the Result. Use ifOk:ifError: (or andThen: / mapError:) when a failure should be logged or retried rather than crashing the caller.

(WebApp supervise)
  ifOk:    [:sup | Logger info: "app started with " , sup count asString , " children"]
  ifError: [:e   | Logger error: e message]

pool startChild
  ifOk:    [:worker | worker process: job]
  ifError: [:e      | Logger warn: "worker start failed: " , e message]

Idempotent terminate. terminate: / terminateChild: naturally express "make sure this child is gone" — no special-casing required.

// Before ADR 0080 — had to swallow Error because not_found raised
[app terminate: Counter] on: Error do: [:_e | nil]

// After — idempotent: returns Result ok: nil whether fresh terminate or already gone
(app terminate: Counter) unwrap
// real failures still surface as Result error: (beamtalk_error terminate_failed)
(app terminate: Counter) ifError: [:e | Logger warn: e message]

See ADR 0080 §Migration Path for the full mechanical rewrite guide and common gotchas (chained sends on the return value, type-narrowing in tests, REPL display changes).

BEAM Mapping

BeamtalkBEAM
Supervisor subclass:-behaviour(supervisor) with one_for_one
DynamicSupervisor(C) subclass:-behaviour(supervisor) with simple_one_for_one
supervisesupervisor:start_link({local, Module}, Module, nil), in the caller, then unlink
spawn / spawnWith: argssupervisor:start_link(Module, Args), in the caller, then unlink
spawnAs: n / spawnWith: args as: nsupervisor:start_link({local, N}, Module, Args), then unlink
named: nwhereis(N) plus a class check
currentwhereis(Module)
nested X supervisionSpecchild spec {beamtalk_supervisor, start_supervisor_child, [Module, Args]} → Module:start_link(Args)
countsupervisor:count_children/1 (active count)
childrensupervisor:which_children/1 (running child ids)
which: Classfind child by module in which_children result
withShutdown:shutdown field in child spec (default 5000ms workers, infinity supervisors; #brutalKill → brutal_kill)
childShutdownshutdown field of the simple_one_for_one child spec
configuration methodsModule:init(Args), run in the supervisor process
argsthe Args passed to init/1
stopgen_server:stop/1

Actor Named Registration (ADR 0079)

Actors can be registered under a Symbol name so they can be looked up without passing a reference around, and so supervised restarts stay addressable. Named lookups are class-checked — Counter named: #counter only returns the registered process if it is a Counter (or subclass).

// Atomic spawn + register — prefer this when the name is known up front
c := (Counter spawnAs: #counter) unwrap
c := (Counter spawnWith: #{#count => 10} as: #counter) unwrap

// Register an already-spawned actor (not atomic w.r.t. spawn)
(c registerAs: #counter) onSuccess: [:c | c increment]

// Typed lookup — Result(Self, Error), so `Counter named:` narrows to Counter
engine := (WorkflowEngine named: #engine) unwrap
(Logger named: #counter)   // => Result error: (beamtalk_error wrong_class)

// Instance queries
c registeredName    // => #counter  (or nil if unnamed)
c isRegistered      // => true

// Idempotent release
c unregister        // => #ok

// Discover all currently-registered Beamtalk actors
Actor allRegistered       // => #(an Actor(Counter), an Actor(Logger))

Restart survival. When a named actor is started under a supervisor (via SupervisionSpec withName:), the runtime dispatches sends through the registered name, not the snapshot pid. Held Counter named: #counter references continue to work after a supervisor restart because the name is re-registered atomically in the restarted process's gen_server:start_link({local, Name}, ...) call.

Errors are surfaced as Result values (or raised as #beamtalk_error{} on direct send):

KindWhen
name_registeredanother process is already registered under the name
name_not_registerednamed: lookup found nothing
wrong_classnamed: lookup found a process of a different class
reserved_namename is in the OTP kernel / stdlib blocklist
no_such_processsend through a {registered, Name} proxy whose name has vanished

See ADR 0079 for the full design and exposure table.

Introspecting the Live Supervision Tree (ADR 0092)

Where supervision syntax declares a tree, Node current processes lets you walk the live one — the dynamic counterpart to Node current actors, and the process-structure twin of SystemNavigation. It returns a navigable SupervisionTree snapshot of the running OTP supervision tree, built as a thin wrapper over supervisor:which_children (no new bookkeeping process).

tree := Node current processes unwrap   // == ProcessNavigation default tree
tree root                          // => the snapshot root SupervisionNode
tree size                          // => total node count
tree do: [:node | Transcript showCr: node printString]
tree select: [:node | node isSupervisor]
tree findClass: Counter            // => every running Counter as SupervisionNodes
tree nodesOfKind: #beamtalkActor   // => List(SupervisionNode)

Each SupervisionNode is an immutable record:

node pid               // => a Pid | nil   (nil for a child mid-restart)
node registeredName    // => Symbol | nil
node kind              // => #beamtalkSupervisor | #beamtalkActor
                       //    | #otpSupervisor | #otpProcess | #restarting
node behaviourClass    // => Class | nil   (nil for foreign OTP processes)
node childCount        // => Integer       (live children; supervisors only)
node strategy          // => Symbol | nil  (#oneForOne … ; supervisors only)
node restartIntensity  // => Dictionary | nil  (configured #{#maxRestarts, #window})
node children          // => List(SupervisionNode)
node parent            // => SupervisionNode | nil
node isSupervisor      // => Boolean
node isBeamtalk        // => Boolean
node status            // => Dictionary | nil   (LAZY — see below)

The kind field drives rendering: a Beamtalk class badge for #beamtalkActor / #beamtalkSupervisor (with behaviourClass populated), a foreign-process badge for #otpSupervisor / #otpProcess. A child OTP is currently restarting carries kind => #restarting and pid => nil — the snapshot never crashes on a process caught mid-restart.

Snapshot semantics. Construction freezes the tree once; iterating it never re-enters OTP, so a walk is internally consistent and can never deadlock or block on a busy process. Construction itself is not atomic, so the snapshot is a best-effort point-in-time view — re-call Node current processes to refresh. A node whose pid has since died is detected lazily: node status returns nil rather than raising.

Lazy state. node status is not captured at snapshot time. Calling it issues a timeout-guarded sys:get_status against the node's pid then — returning a Dictionary for an alive, sys-compliant process, or nil for one that is dead, timed out, or not sys-compliant.

Scopes and scale. ProcessNavigation default (what Node current processes wraps) filters runtime plumbing; ProcessNavigation system shows everything, including runtime internals — a privileged view (ADR 0091). A from: constructor roots a walk at a Supervisor handle or a Pid, returning a Result (the root may be dead). A simple_one_for_one DynamicSupervisor with more children than the cap is reported truncated with its childCount instead of materialising every child; opt into full expansion with ProcessNavigation from: aSup limit: n.

ProcessNavigation system tree size                 // everything, incl. infra
(ProcessNavigation from: aSup) unwrap tree         // a rooted subtree
(ProcessNavigation from: aStoppedSup)              // => Result error: (beamtalk_error stale_handle)

See ADR 0092 for the full design.


Named Actor Registration (ADR 0079)

Named actor registration gives a process a stable identity (a Symbol) that survives supervised restarts. A name-resolving proxy re-resolves the name on every message send, so a held reference keeps working even when the underlying actor is restarted with a fresh pid.

Under the hood this maps directly to OTP's process registry (erlang:register/2, gen_server:start_link({local, Name}, ...)), so registered Beamtalk actors show up in observer, recon, and erlang:registered/0 with the names you chose.

API Surface

MethodKindReturnsSemantics
Class spawnAs: nameclass-sideResult(Self, Error)Atomic spawn + register. Equivalent to gen_server:start_link({local, Name}, ...) — the name is registered during process startup.
Class spawnWith: initArgs as: nameclass-sideResult(Self, Error)Same as spawnAs: but with initialization arguments.
Class named: nameclass-sideResult(Self, Error)Look up a registered actor. Self resolves to the receiver class at the call site, so Counter named: returns a Counter.
Actor allRegisteredclass-sideList(Actor)Enumerates currently-registered Beamtalk actors. Excludes raw OTP-registered processes (kernel_sup, logger, …).
actor registerAs: nameinstanceResult(Self, Error)Register an already-spawned actor. Non-atomic — prefer spawnAs: when the name is known up front.
actor unregisterinstanceSymbol#ok. Idempotent — unregistering an unregistered actor is not an error.
actor registeredNameinstanceSymbol or nilCurrently-registered name, or nil.
actor isRegisteredinstanceBooleanWhether the actor currently has a registered name.

Supervised children gain naming through SupervisionSpec withName:, which tells the runtime to start the child with {local, Name} registration so the name is re-established every time the supervisor restarts the child:

EventStore supervisionSpec withName: #eventStore withRestart: #permanent

Errors

Registration returns Result(Self, Error) rather than raising — callers branch explicitly on outcome:

ConditionResult
spawnAs: / registerAs: — duplicate registrationResult error: (beamtalk_error name_registered)
spawnAs: / registerAs: — name is in the reserved listResult error: (beamtalk_error reserved_name)
spawnAs: / registerAs: — non-Symbol nameResult error: (beamtalk_error type_error)
Class named: — no actor registered under this nameResult error: (beamtalk_error name_not_registered)
Class named: — name is registered but the actor is not a Class or subclassResult error: (beamtalk_error wrong_class)
Send to a proxy whose name is not currently registered (the target died or was unregistered after lookup)Raises beamtalk_error no_such_process

The asymmetry is deliberate: named: returns a Result because name-absence is an expected outcome the caller must branch on; sending to a vanished proxy raises because the caller has already committed to a send.

Worked Example — Migrating from Supervisor which:

Before named registration

The pre-ADR pattern uses a supervisor-local lookup (which:) and an initialize hook to re-wire dependencies after each restart:

typed Supervisor subclass: ExduraSupervisor
  strategy -> SupervisionStrategy => #restForOne
  childSpecs -> List(SupervisionSpec) =>
    storeSpec := EventStore supervisionSpec withRestart: #permanent
    poolSpec := ActivityWorkerPool supervisionSpec withRestart: #permanent
    engineSpec := WorkflowEngine supervisionSpec withRestart: #permanent
    #(storeSpec, poolSpec, engineSpec)

  // Runs after the initial start to cache pids (not after restarts).
  initialize -> Nil =>
    store := (self which: EventStore) unwrap
    pool := (self which: ActivityWorkerPool) unwrap
    engine := (self which: WorkflowEngine) unwrap
    engine initWithStore: store pool: pool
    nil

After named registration

Naming each child eliminates the initialize hook, and the supervisor strategy is freed from the rewire-on-restart constraint:

typed Supervisor subclass: ExduraSupervisor
  strategy -> SupervisionStrategy => #oneForOne
  childSpecs -> List(SupervisionSpec) => #(
    EventStore supervisionSpec withName: #eventStore withRestart: #permanent,
    ActivityWorkerPool supervisionSpec withName: #workerPool withRestart: #permanent,
    WorkflowEngine supervisionSpec withName: #workflowEngine withRestart: #permanent
  )
  // No initialize hook — WorkflowEngine looks up its dependencies by name.

WorkflowEngine now calls (Actor named: #eventStore) unwrap at use-time — automatically picking up the current pid across restarts — and cross-tree consumers (HTTP handlers, REPL workspaces, tests) can reach supervised actors directly without routing through the supervisor.

Proxy Semantics

Class named: returns a lightweight name-resolving proxy. The proxy does not cache a pid; each message send re-resolves the name via the Erlang runtime. This is the key restart-survival property:

engine := (WorkflowEngine named: #workflowEngine) unwrap
engine runWorkflow: w1    // resolves #workflowEngine, sends to that pid
// (#workflowEngine crashes; the supervisor restarts it under the same name)
engine runWorkflow: w2    // re-resolves #workflowEngine, sends to the NEW pid

A few caveats the proxy intentionally does not paper over:

Reserved Names

A static blocklist of OTP-kernel atoms is rejected at registration time, regardless of whether the corresponding process is currently running. Attempting spawnAs: #logger or spawnAs: #kernel_sup returns Result error: (beamtalk_error reserved_name).

The reserved set covers:

See beamtalk_actor_registry:reserved_name/1 in the runtime for the authoritative list and the policy rationale (ADR 0079 §Errors).

Scope

This release covers local (per-node) registration. Cluster-wide (#global) and pluggable ({via, Module, Term}) scopes are deferred to a future ADR — the API is designed to admit them additively via a scope: keyword. Users who need cluster registration today can call the Erlang global module via FFI.

BEAM Mapping

BeamtalkBEAM
Class spawnAs: #foogen_server:start_link({local, foo}, Module, #{})
Class spawnWith: args as: #foogen_server:start_link({local, foo}, Module, args)
actor registerAs: #fooerlang:register(foo, Pid)
actor unregisterBeamtalk-wrapped idempotent erlang:unregister(foo) — Beamtalk catches the badarg raw Erlang raises when the name is absent and returns ok, so repeated/unnecessary unregisters are safe
Class named: #fooerlang:whereis(foo) + Beamtalk class check via '$beamtalk_actor' process-dict marker
Actor allRegisterederlang:registered/0 filtered by the process-dict marker
Proxy send (proxy foo)gen_server:call(foo, ...) — name-resolved per send
SupervisionSpec withName:Child MFA uses {beamtalk_actor_registry, spawnAs, [Name, Module, ...]} so the supervisor re-registers the name on every restart

Pattern Matching

Smalltalk lacks pattern matching - this is a major ergonomic addition.

Match Expression

The match: keyword message takes a block of pattern arms separated by ;:

// Basic match with literals
x match: [1 -> "one"; 2 -> "two"; _ -> "other"]

// Variable binding in patterns
42 match: [n -> n + 1]
// => 43

// Symbol matching
status match: [#ok -> "success"; #error -> "failure"; _ -> "unknown"]

// String matching
greeting match: ["hello" -> "hi"; _ -> "huh?"]

// Guard clauses with when:
x match: [
  n when: [n > 100] -> "big";
  n when: [n > 10] -> "medium";
  _ -> "small"
]

// Negative number patterns
temp match: [-1 -> "minus one"; 0 -> "zero"; _ -> "other"]

// Match on computed expression
(3 + 4) match: [7 -> "correct"; _ -> "wrong"]

// Array destructuring in match arms (BT-1296)
#[10, 20] match: [
  #[h, t] -> h + t;
  _ -> 0
]
// => 30

// Dict/map destructuring in match arms (BT-1296)
#{#event => "click", #x => 5} match: [
  #{#event => evName} -> evName;
  _ -> "unknown"
]
// => "click"

// Nested array patterns
#[#[1, 2], 3] match: [
  #[#[a, b], c] -> a + b + c;
  _ -> 0
]
// => 6

// Constructor patterns (Result ok:/error: only in this release)
(Result ok: 42) match: [
  Result ok: v    -> v;
  Result error: _ -> 0
]
// => 42

// The sub-pattern after `ok:` / `error:` may be a variable, `_`, a literal,
// or a nested tuple `{a, b}` / map `#{#k => v}` pattern (BT-5277). Array
// (`#[...]`) and binary sub-patterns are not supported there.
(Result ok: {3, 4}) match: [
  Result ok: {a, b} -> a + b;
  Result error: _   -> 0
]
// => 7

// Binary patterns (BT-663; BT-4096, BT-4097, BT-4143)
(Binary fromBytes: #(3, 104, 105, 33, 99)) match: [
  <<n:8, payload:n/binary, rest/binary>> -> payload toBytes;
  _ -> #()
]
// => #(104, 105, 33): a size may be a literal, a variable bound by an
// earlier segment, a parameter/local, or a parenthesized arithmetic
// expression over them (no message sends: bind `p size` to a local first).
(Binary fromBytes: #(10, 9)) match: [
  <<0:1, v:7, rest/binary>> -> v;
  _ -> -1
]
// => 10: integer literal values match exactly.
(Binary fromBytes: #(234, 7)) match: [
  <<_:3, v:5, rest/bits>> -> v;
  _ -> -1
]
// => 10: bits/bitstring match possibly-unaligned bits.
(Binary fromBytes: #(234)) match: [
  <<_:3, rest/bits>> -> rest class;
  _ -> nil
]
// => Bitstring: an unaligned tail is a Bitstring (ADR 0141); use
// bitSize/toBits on it, not the byte protocol. An aligned tail is a Binary.
(Binary fromBytes: #(0, 65)) match: [
  <<c/utf16, rest/binary>> -> c;
  _ -> -1
]
// => 65: utf16/utf32 decode 2-/4-byte big-endian code units.
(Binary fromBytes: #(18, 52, 7)) match: [
  <<v:2/unit:8, rest/binary>> -> v;
  _ -> -1
]
// => 4660: unit: multiplies the size — 2 units of 8 bits read 16 bits.
(Binary fromBytes: #(63, 248, 0, 0, 0, 0, 0, 0)) match: [
  <<1.5/float, rest/binary>> -> rest size;
  _ -> -1
]
// => 0: float literal values match exactly, like integers.
"hi" match: [
  <<"hi", rest/binary>> -> rest size;
  _ -> -1
]
// => 0: string literal values match exact bytes (UTF-8 for non-ASCII);
// <<$A>> matches byte 65. With a utf type a string matches per
// character instead: <<"hi"/utf16>> matches bytes #(0, 104, 0, 105).

// Binary construction (ADR 0143): the same <<...>> in expression position
// builds a binary, so a built value matches back with the same segments.
payload := Binary fromBytes: #(104, 105)
len := payload size
frame := <<16:8, len:24, payload/binary>>
frame toBytes
// => #(16, 0, 0, 2, 104, 105)
frame match: [
  <<16:8, n:24, rest:n/binary>> -> rest toBytes;
  _ -> #()
]
// => #(104, 105)

// Nil pattern — matches nil exactly (BT-2854, ADR 0107)
value := nil
value match: [
  nil -> "was nil";
  s :: String -> s;
  _ -> "other"
]
// => "was nil"

// Type patterns — bind and test runtime class (BT-2855, ADR 0107)
x := "hello"
x match: [
  nil -> "nil";
  s :: String -> s size;
  n :: Integer -> n + 1;
  _ -> "other"
]
// => 5

// Guard scoped over the type-pattern binding
x := 42
x match: [
  n :: Integer when: [n > 100] -> "big";
  n :: Integer -> "small";
  _ -> "other"
]
// => "small"

// Mixing type patterns with literal and wildcard patterns
x := "hi"
x match: [
  nil -> 0;
  s :: String -> s size;
  _ -> -1
]
// => 2

Binary patterns match bytes and bits: <<first:8, _/binary>> binds the first byte, <<_:8, rest/binary>> the tail. A segment is value, value:size, value/specifiers, or value:size/specifiers. The specifiers are joined with - and name a type, integer (the default), float, binary/bytes, bits/bitstring, utf8, utf16, or utf32, plus signed/unsigned, big/little/native, and unit:N (1 to 256). A size is an integer literal, a variable, or a parenthesized expression. In a pattern, a size must be a guard expression, because the BEAM evaluates it during the match: literals, variables and +, -, * over them. A message send (body:(p size - 1)/binary), a field read, or any other operator (/, which always answers a float; a comparison; %) in a pattern size is a compile error at that expression (BT-5285). The hint says to bind the value to a variable before the match (or, when the size uses a variable bound by the same pattern, to split the match in two): room := p size - 1, then <<pad:8, body:(room - pad)/binary, _tail:pad/binary>>. A construction size has no such limit (see below). It counts units: the unit is 1 bit for integer, float and bits, and 8 bits for binary, so v:2/unit:8 reads 16 bits and p:3/binary reads 3 bytes. Without a size, an integer is 8 bits, a float is 64, and a binary/bits segment takes the rest. A size may name a variable bound by an earlier segment of the same pattern (<<n:8, payload:n/binary>>), a parameter, or a local. A size that names an earlier segment of the same binary, or a size expression, is only supported when the binary pattern is the whole arm pattern — match the enclosing value first, then the binary. A binary nested inside a tuple in a match: arm is matched after the tuple, so its sizes may name a variable the tuple or an earlier nested binary binds ({n, <<head:n/binary, _/binary>>}). Destructuring assignment does not accept nested patterns (an annotated element x :: T is not nested). A binary pattern matches a String subject by its UTF-8 bytes, whether it is the whole arm pattern or nested inside a tuple ({#ok, <<71, 69, 84, 32, rest/binary>>} matches {#ok, "GET /x"}); /binary segments always bind a Binary (BT-4173, BT-4223). A /bitstring (/bits) segment binds whatever the bits are: a Binary when they are a whole number of bytes, otherwise a Bitstring (ADR 0141), which understands only bit-level messages (bitSize, toBits, concat:, asBinary). A type pattern b :: Bitstring matches exactly the unaligned values; b :: Binary never matches one. Every _ in a pattern is a fresh anonymous variable, so {#a, _, x, _} compiles.

Binary segment values and checks (BT-4097, BT-4143, BT-4376). Besides a variable or _, a segment value may be a literal, which must match exactly:

These segment rules are compile errors, with erlc's wording: a negative literal size; a size or unit: on a utf8/utf16/utf32 segment; a unit: without a size on an integer or float segment (a sizeless binary or bits segment may take one: rest/binary-unit:16 matches a tail whose bit length is a multiple of 16); and a unit: that conflicts with the one the type implies. bits/bitstring imply unit 1 and bytes implies unit 8, so x:2/bits-unit:8 is "conflict in unit specification for bit field: '8' and '1'", while bytes-unit:8 and binary-unit:N are accepted.

An arm that can never match is a warning, as it is in erlc. Examples: a literal that does not fit its segment (<<300>> in the default 8 bits, or <<-1:8>> in an unsigned segment); an integer literal in a binary/bits segment; a float literal in a non-float segment; and a float size other than 16, 32 or 64 bits (size × unit). A non-ASCII character literal (U+0080 to U+00FF) in an 8-bit integer segment (the default size, or an explicit size × unit of 8 such as $é:8) also warns: <<$é>> matches the single byte 233 (its code point), not the UTF-8 bytes that <<"é">> matches, so write "é" or $é/utf8 instead. To silence one of these warnings, use @expect. --warnings-as-errors turns them into errors.

Binary construction (ADR 0143, BT-4346/4347/4348). <<...>> where an expression is expected builds a binary, with the same segment grammar as a binary pattern: <<v:4, p/binary>>, <<s:8/unit:2>>, <<1.5/float>>, <<$A>>, <<"hi">>, <<h:16/big-unsigned-integer>>. A leading << opens a construction; << is not a binary operator, so an infix a << b is a parse error. Every pattern example above reads as construction, so build-then-match round-trips:

v := 4660
<<v:16/little>> toBytes                       // => #(52, 18)
<<-2:16/signed>> toBytes                      // => #(255, 254)
<<1.5:32/float>> toBytes                      // => #(63, 192, 0, 0)
<<"é">> toBytes                               // => #(195, 169) (UTF-8 bytes)
<<"hi"/utf16>> toBytes                        // => #(0, 104, 0, 105)
name := "hé"
<<name/binary>> toBytes                       // => #(104, 195, 169)
<<(name size):8, name/binary>> toBytes        // => #(2, 104, 195, 169)
<<1:3>> class                                 // => Bitstring
(<<7:3, 10:5>> match: [<<f:3, w:5>> -> {f, w}; _ -> nil])   // => {7, 10}

An arm body is an expression, not a block. pattern -> [ ... ] answers the block as a value and does not run its statements: 1 match: [1 -> [2 + 3]; _ -> [0]] answers a Block, not 5. A zero-parameter block body alongside non-block arms warns (MatchArmBlock: "this match: arm answers a Block without running it"); a match whose every arm is a block literal is read as an intentional dispatch table and stays silent. In an actor or Server method, such a block that writes a field or sends to self (#tick -> [self.count := self.count + 1]) is additionally a compile error. For an arm that needs several statements, call a method (#tick -> self tick), or evaluate the block in place (#tick -> [ ... ] value). A single field write can be the arm itself ({#tick, n} -> self.count := self.count + n). Suppress a deliberate block-valued arm with @expect match_arm_block, or the whole package with match-arm-block = "off" under [diagnostics].

Arms do not thread assignments. An arm body is not a block, so assigning an enclosing local inside one has no effect: the compiler warns (Assignment to x inside a match arm has no effect) and --warnings-as-errors rejects it. Bind the match's answer instead: timeout := value match: [...].

Type patterns test the runtime class of the scrutinee and bind the value to the named variable, narrowed to that class. Subsequent arms see the scrutinee type narrowed by difference (e.g. after a s :: String arm, the remaining arms see the type minus String).

Supported classes (ADR 0107): a class without subclasses is tested for its exact class. Supported classes: String, Integer, Float, List, Dictionary, Boolean (uses the is_boolean/1 BIF; True/False use exact atom guards — all three are stdlib primitives tested by a BIF/atom guard rather than a user-class hierarchy check), True, False, Symbol, Nil, UndefinedObject, Block, Pid, Reference, Port, Bitstring (ADR 0141: is_bitstring and not is_binary, so it never matches a Binary), user-defined Value subclasses, Actor subclasses, and Supervisor/DynamicSupervisor subclasses (BT-2870).

Classes with subclasses (ADR 0107 Phase B, BT-4319): binding :: Shape where Shape has subclasses Circle/Square matches per isKindOf: — instances of Shape and of every subclass match, and the binding is narrowed to Shape. The arm looks the value's class up in the live class table at run time, so subclasses declared in other files or added by hot reload are matched too. Abstract classes work the same way. Put the most specific arm first; an arm for a subclass after its base class's arm is unreachable. This is how to dispatch over an exception hierarchy:

ex match: [
  h :: HTTPError -> self protocolError: h;       // also HTTPError414, …
  t :: TransportError -> self protocolError: t;
  _ -> self internalError: ex
]

Two things to know. A class with no visible subclass tests its exact class first and, only for an instance of a different user class, falls back to the same runtime lookup — so a subclass declared in another package or loaded later by hot reload still matches, without changing the arm. And when: guards stay comparison/arithmetic-only: _ when: [e isKindOf: HTTPError] -> … is rejected ("complex guard expression"), so use the type pattern instead. A Future scrutinee never matches a user-class arm (it is not awaited). An abstract class with no subclass visible to the compiling package is still rejected ("is abstract; type patterns require a concrete subclass"), even if its concrete subclasses live in a downstream package.

Binary was the first subclass-aware pattern (BT-4228). Binary is sealed and String is its only subclass, so b :: Binary is accepted and compiles to a closed, constant-time subclass-aware test: it matches a bare binary (valid UTF-8 or not) or a String, agreeing with isKindOf: Binary. To tell bytes from text, put the String arm first:

value match: [
  s :: String -> #text;
  b :: Binary -> #bytes;   // only bare binaries reach here
  _ -> #other
]

For exhaustiveness checking, a b :: Binary arm covers a String member of the scrutinee type, but a Binary member is not treated as a closed leaf (so matchExhaustive: over a Binary | Nil scrutinee cannot be proven; use match:).

Type patterns nest, and _ :: T binds nothing (BT-5294). x :: T is a sub-pattern of a tuple, map, Result ok:/error: constructor, or array pattern, so "a pair whose second element is an Integer" is one arm: info match: [{_, port :: Integer} -> port; _ -> 0], r match: [Result ok: n :: Integer -> n; _ -> 0], #[h :: Integer, t]. _ :: T tests the class without naming the value: error match: [_ :: ExitError -> #exit; _ -> #error]. In a match: arm a nested test is the same runtime class test as a top-level x :: T (in a := destructuring, x :: T stays an unchecked annotation, BT-5284). The shape (tuple size, constructor tag, map keys) matches first; then each type test runs in source order, left to right; then the arm's when: guard runs with every binding in scope (the type checker narrows each nested x :: T to T inside the arm, like a top-level x :: T arm, BT-5332), so a guard such as n > 5 never sees a value the type test rejected. Where the scrutinee's type at a nested position is known (tuple element, map-shape value, Result ok:/error: payload), the binding is the intersection of that type and T, so {#ok, l :: List} over a Tuple(Symbol, List(Integer)) binds List(Integer) (BT-5336); an unknown or Object position, or one disjoint from T, binds the bare T (an Object pattern stays unchecked). A miss at any step falls through to the next arm. It nests in a #( ... ) list pattern too, element or tail: #(n :: Integer | rest) (BT-5301). Not supported: a type pattern in a pattern that also nests a binary pattern, or as a nil/true/false annotation.

Four runtime-representation nuances (see ADR 0107 Implementation for the full codegen rationale):

Supported pattern types:

PatternExampleDescription
Wildcard_Matches anything
Literal integer42Exact integer match
Literal float3.14Exact float match
Literal string"hello"Exact string match
Literal symbol#okExact symbol match
Literal character$aExact character match
Negative number-1Negative integer/float match
VariablexBinds matched value to name
Tuple{a, b}Destructure tuple in assignment and match arms ({a, b} is also a tuple literal expression — see Tuple Literals)
Array#[a, b]Match and destructure an Array by exact size; nested arrays supported; element names must be distinct in destructuring (BT-5052)
List#(), #(a, b), #(h | t), #(a, b | rest)Match a List: without |, exactly that many elements; with it, at least that many, the tail binding the rest. Elements and tail are full patterns, so lists nest (#(a | #(b | t))). See List Patterns (BT-5301)
Array rest#[a, ...rest]Destructure first elements, bind remaining to a sub-array (destructuring assignment only); the rest name must not repeat an element name (BT-5050)
Dict/Map#{#k => v}, #{?#k => v}, #{?"k" => v = 0}Match a Dictionary containing key #k, bind value to v; partial match (other keys ignored). A ? key is optional: absent binds nil or the = literal default. See Optional Map Keys (ADR 0155)
ConstructorResult ok: vMatch sealed type by constructor (Phase 1: Result only)
Binary<<n:8, payload:n/binary>>Match bytes/bits; sizes may name earlier segments, params/locals, or parenthesized exprs; bits for unaligned tails; utf8/utf16/utf32 and unit:N; integer, float, character and string literal values; a misfit literal warns (BT-663, BT-4096, BT-4097, BT-4143, BT-4376)
NilnilMatches nil exactly; narrows subsequent arms to exclude Nil (BT-2854, ADR 0107)
Typex :: StringBind x and test runtime class; x is narrowed to the named class in the arm body and guard. A class with subclasses matches its subclasses' instances too (isKindOf: semantics, BT-4319); a class without subclasses matches exactly that class; sealed Binary is subclass-aware — see restrictions below (BT-2855, ADR 0107)

Exhaustiveness checking (BT-1299): match: on a sealed type with constructor patterns must cover all known variants or include a wildcard _ arm, or the compiler emits an error:

// Compile error: missing error: arm
r match: [Result ok: v -> v + 1]

// Fine: all variants covered
r match: [Result ok: v -> v + 1; Result error: _ -> 0]

// Fine: wildcard suppresses the check
r match: [Result ok: v -> v + 1; _ -> 0]

Advisory singleton-union exhaustiveness (BT-2745, ADR 0102): when the type checker knows a match: scrutinee is a closed union of #symbol singletons, it emits a warning (never an error) for any uncovered members:

// direction :: #north | #south | #east | #west
direction match: [
  #north -> 0;
  #south -> 180;
  #east  -> 90
]
// ⚠ Warning: non-exhaustive match: `#west` is not handled (residual type: `#west`)

This check is advisory — it fires only when the scrutinee type is a union of pure #symbol singletons (not Dynamic, open Symbol, or mixed unions). An unguarded _ -> wildcard silences the warning; guarded arms do not count as coverage.

Asserted exhaustiveness — matchExhaustive: (BT-2763, ADR 0106): matchExhaustive: is an opt-in, stricter variant of match: that asserts exhaustiveness. It parses identically to match: (same patterns, guards, and destructuring), but the check runs at error severity instead of warning:

// direction :: #north | #south | #east | #west

// Compile error: matchExhaustive: proves this is NOT exhaustive
direction matchExhaustive: [
  #north -> 0;
  #south -> 180;
  #east  -> 90
]
// ⛔ Error: non-exhaustive matchExhaustive: `#west` is not handled (residual type: `#west`)

// Fine: all four members covered — silent, no diagnostic
direction matchExhaustive: [
  #north -> 0;
  #south -> 180;
  #east  -> 90;
  #west  -> 270
]

// Fine: an unguarded wildcard is still full coverage
direction matchExhaustive: [
  #north -> 0;
  _      -> -1
]

If the scrutinee's type is not a closed union of #symbol singletons (Dynamic, a bare/open Symbol, or a mixed union), nor a closed Known | Nil union (or small closed union of concrete leaf classes) covered by nil/Type patterns (ADR 0107), matchExhaustive: cannot verify the assertion and fails loudly rather than staying silent:

x matchExhaustive: [#ok -> 1; _ -> 0]
// ⛔ Error: cannot verify `matchExhaustive:` is exhaustive — scrutinee type
//    `Dynamic` is not a closed union of symbol singletons, `nil`, or
//    concrete leaf classes

Result is a closed pair (BT-5278). A Result(T, E) scrutinee is accepted when the arms are Result ok: / Result error: constructor patterns: ok: and error: are the two variants, exactly as for plain match:. A missing variant is the usual compile error (Non-exhaustive match: on sealed type \Result`), an arm after both variants are covered is flagged as unreachable, and a variant matched only by a refutable nested pattern (Result ok: {a, b}) is an error because the checker cannot prove it total — add Result ok: vor a_` arm:

r matchExhaustive: [
  Result ok: v    -> v;
  Result error: _ -> 0
]

Plain match:'s advisory warning behaviour is unchanged by matchExhaustive: — the two checks are independent, and only the keyword you write selects between them.

Guard expressions support: >, <, >=, <=, =:=, =/=, /=, +, -, *, /

Destructuring in Match Arms

Pattern matching can bind variables in match arms:

// Variable captures the matched value
42 match: [x -> x + 1]
// => 43

// Variable binding with guard
10 match: [x when: [x > 100] -> "big"; x when: [x > 5] -> "medium"; _ -> "small"]
// => "medium"

// Tuple destructuring in match arms
t := Erlang erlang list_to_tuple: #(#ok, 42)
t match: [{#ok, v} -> v; {#error, _} -> 0]
// => 42

Destructured locals are typed (BT-4487): in a destructuring assignment, a plain-variable element of a tuple pattern takes the type of the matching position of a Tuple(A, B) right-hand side, the same as t at: i with a literal index. An Object, Dynamic or unresolved-generic position stays Dynamic. A right-hand side that is not a same-arity tuple (a bare Tuple, a different arity, a mixed union) binds Dynamic. A narrower declared type than the position can prove draws the usual type-mismatch warning, so narrow first with isKindOf:.

Annotated elements (BT-5284): a tuple, array or map destructuring element may carry name :: Type, the same :: form as the match-arm type pattern: {_, sid :: Integer, es :: Boolean} := frame, #[a :: Integer, b] := xs, #{#id => i :: Integer} := m. Here the annotation is the declared type of the local, trusted exactly like x :: T := expr: it is not a runtime class test (a match arm's x :: T is), so a value of another class still binds. A tuple position whose type is known and clashes with the annotation draws the usual assignment type-mismatch warning. A #( ... ) list destructure takes them too (#(n :: Integer | t) := xs, #(a :: Integer, b) := xs, BT-5301). Annotations on a ...rest element are not supported.

Pattern failures (BT-3943): a destructuring assignment whose tuple size, literal slot or array shape does not match, and a match: with no matching arm, raise a structured #pattern_mismatch error (class RuntimeError, the offending value in the error details). A map destructure with a missing key raises #key_error instead.

[{#ok, _v} := {#error, 42}] on: Error do: [:e | e kind]
// => #pattern_mismatch

Optional Map Keys (ADR 0155)

A map-pattern key marked with a leading ? is optional. When the key is absent, the pattern still matches and binds nil, or the default written after the value as = literal. This works for symbol and string keys alike, in match: arms and in destructuring, and uses the same ? that marks an optional key in a shape type:

#{#host => host, ?#port => port = 80, ?#path => path} := #{#host => "a"}
port
// => 80
path
// => nil

#{"id" => 1} match: [
  #{"id" => id, ?"priority" => p :: Integer} -> {id, p};
  _ -> #nomatch
]
// => {1, nil}

Types. An optional binding has the type a required binding would have, joined with Nil, or with the default's type when there is one. Over #{?#port => Integer}, ?#port => p binds Integer | Nil and ?#port => p = 80 binds Integer. Over an untyped Dictionary the binding stays Dynamic, but ?"n" => n :: Integer binds Integer | Nil (or Integer with a fitting default). A default that does not fit the :: T warns. An optional key that no closed shape names is always absent, and warns.

Lowering. Required keys stay in the native Erlang map pattern. An optional key is one maps:get/3 with its constant default, or one maps:find/2 when it carries a type test. No closure is built and nothing is dispatched, so a pattern costs less than the equivalent at:ifAbsent: lookups.

List Patterns (BT-5301)

#( ... ) is a pattern as well as a literal: the pattern form of the list literal and of its cons form #(head | tail) (List Cons Literal, ADR 0012). It matches a List (an Erlang list) and nothing else: not an Array, a Tuple, a String or nil.

PatternMatches
#()the empty list
#(a), #(a, b)a list of exactly one, two, ... elements
#(h | t)a list of at least one element; t is the rest (possibly #())
#(a, b | rest)a list of at least two elements

Elements and the tail are full patterns: literals, tuples, maps, nested lists (#(a | #(b | t)), #(#(x, y) | _)) and x :: T.

pairUp: xs acc: acc =>
  xs match: [
    #() -> acc reversed;
    #(a) -> (acc addFirst: {a}) reversed;
    #(a, b | rest) -> self pairUp: rest acc: (acc addFirst: {a, b})
  ]

sum: xs :: List(Integer) -> Integer =>
  xs matchExhaustive: [
    #() -> 0;
    #(h | t) -> h + (self sum: t)
  ]

Over a List(T) scrutinee an element binds T and a tail binds List(T). In a match: arm a nested x :: T is a runtime class test, like any nested type pattern (BT-5294).

Exhaustiveness. matchExhaustive: over a List scrutinee proves the arms cover every length: #() plus #(h | t) is exhaustive, and so is #(), #(a), #(a, b | rest). Only an unguarded arm whose elements are all variables or _ counts; a missing shape is a compile error that names it (`#()`, `#(_)`, `#(_, _ | _)`), and an arm after full coverage warns as unreachable.

Destructuring. A cons or empty pattern on the left of := matches the same way and raises #pattern_mismatch when the value is not a list of that shape:

#(h | t) := #(10, 20, 30)      // h = 10, t = #(20, 30)
#(a | #(b | t)) := #(4, 5, 6)  // a = 4, b = 5, t = #(6)
#(h | t) := #()                // raises #pattern_mismatch

A fixed-length #(a, b) := xs keeps its older positional meaning: it reads xs at: 1, xs at: 2, ... from any sequence (List or Array) and ignores extra elements, annotated or not. Use a cons pattern for an exact list shape. As elsewhere in destructuring, x :: T is a trusted annotation, not a runtime test (BT-5284), and the positional form may still end in ...rest (#(a :: Integer, ...rest) := xs). A cons or empty destructure may nest tuple, list and map patterns; an array, binary or constructor pattern inside one is a compile error (match the value with match: instead). The positional form takes no nested patterns, like #[a, b] :=. In a match: arm a list pattern takes its tail with |; ...rest there is rejected.

Rest Patterns in Destructuring (BT-1251)

The ...identifier syntax in array destructuring captures remaining elements:

#[first, ...rest] := #[1, 2, 3, 4, 5]
// first = 1, rest = #[2, 3, 4, 5]

#[a, b, ...tail] := #[10, 20, 30, 40]
// a = 10, b = 20, tail = #[30, 40]

#[...all] := #[1, 2, 3]
// all = #[1, 2, 3]

#[head, ..._] := #[1, 2, 3]
// head = 1 (rest discarded)

The rest element must be the last in the pattern. Rest patterns are supported in destructuring assignment only — they are not yet supported in match: arms.

Duplicate names in destructuring patterns (BT-5052, BT-5050). Every element and rest name in a destructuring array pattern must be distinct. #[a, a] := #[1, 2] and #[a, ...a] := #[1, 2, 3] are compile errors ("Variable 'a' is bound multiple times in pattern"). Nested arrays are covered: #[a, #[b, a]] := ... is also an error. match: arms are unaffected — #[a, a] -> ... still matches only when both elements are equal.

Note: Tuple destructuring works in both assignment ({x, y} := expr) and match: arms. A tuple pattern may end with a trailing comma ({x, y,} := expr), like the tuple literal it mirrors. collect: with pattern blocks is not yet supported.

Value of a Destructuring Assignment (BT-3889)

A destructuring assignment evaluates to its right-hand side, as x := expr evaluates to expr. Destructuring is a statement, so this is the value of a body whose last statement it is: a method (class, value-type and actor methods alike), a block, a conditional arm, a protected block (on:do:, ensure:), and the element, accumulator or key a collect:, inject:into: or groupBy: body answers:

swap => {a, b} := self pair       // answers the pair, not nil

#(1, 3) collect: [:x | #(_a, _b) := #(x, 2)]
// => #(#(1, 2), #(3, 2))

A destructure that ends a predicate block (select:, detect:, allSatisfy: and the like) passes its right-hand side, a list, tuple or map, as the predicate, so it raises like any other non-boolean predicate. A groupBy: is a fold like collect: (BT-3897, lowered by BT-3912): in an actor method or at the REPL its block may bind a local, write a field or send to self, and the grouped dictionary is the value wherever the groupBy: sits.

In an actor method, an evaluated block literal ([...] value, [:k | ...] value: x, value:value:) that binds a local, writes a field or sends to self answers its value wherever it sits, and its writes are visible to the operands and statements after it: {[:y | self.count := y] value: 5, self.count} is {5, 5} (BT-3982). Its arguments are evaluated first, in order. One that assigns a local of its own answers its value inside a to:do:, timesRepeat:, whileTrue: or whileFalse: body or condition too (BT-3947; BT-3948 had made it a compile error in an actor method), and one whose block writes an outer local is a local-threading producer like a conditional (see Capturing Variables; BT-4263 for the value: family). Class and value-type methods answer the value everywhere.

The REPL displays the same value. Destructuring is not an expression, so it cannot appear as an operand (r := ({a, b} := pair) is a compile error).

Patterns in Real Code

These sites come from the downstream adoption of the pattern features (BT-5221; verdicts in docs/research/feature-adoption-2026.md). Each is quoted from a public package so the forms shown are ones that compile and run.

A closed set, asserted. exdura declares the lifecycle states once as a type alias, and each wait loop uses matchExhaustive:, so adding a state breaks every loop at compile time. This is the form the package documents in src/workflow/workflow_status.bt; its loops in workflow_handle.bt have the same arms with the bodies adapted to the loop:

type WorkflowStatus = #running | #completed | #failed | #cancelled | #continued_as_new

exec status matchExhaustive: [
  #running -> nil;
  #completed -> exec result;
  #failed -> self error: "failed";
  #cancelled -> self error: "cancelled";
  #continued_as_new -> nil
]

Result constructor patterns replace an isOk ifTrue: ladder when both branches use the value or the error (jamesc/beamtalk-catalina, src/socket.bt):

send: data :: Object -> Result(Nil, Object) =>
  result := self.transport send: self.socket data: data
  self isTraced
    ifTrue: [
      result match: [
        Result ok: _ -> self untimed: #send measurements: #{#data => data};
        Result error: reason -> self event: #send_error measurements: #{
          #data => data,
          #error => reason
        }
      ]
    ]
  result

Type, nil and wildcard arms replace an isKindOf: ladder (jamesc/beamtalk-liquid, src/liquid/renderer.bt):

class stringify: value :: Object | Nil -> String =>
  value match: [
    nil -> "";
    s :: String -> s;
    items :: List -> items inject: "" into: [:acc :: String :each :: Object |
      acc ++ (self stringify: each)
    ];
    _ -> value displayString
  ]

A binary pattern whose size is computed from an earlier segment parses a padded HTTP/2 DATA frame. The size expression room - padLength uses only locals and segments, as the size rules above require; the _ arm is the only place a malformed frame can be reported, because a failed binary match carries no position or reason (jamesc/beamtalk-mint, src/mint_h2frame.bt):

room := payload size - 1
payload match: [
  <<padLength:8, body:(room - padLength)/binary, _padding:padLength/binary>> -> {#ok, {#data, sid, (self flagSet: flags bit: 0), body}};
  _ -> {#error, "DATA frame with invalid padding length"}
]

Map destructuring of an always-complete map, typed by a shape. The shim's token map has every key, with nil for a part the provider did not send, so a map pattern fits and the shape type checks literals at call sites. It does not check the map the shim returns, which arrives as Dynamic (jamesc/beamtalk-oauth, src/oauth_flows.bt):

type TokenResponse = #{
  #access_token => String | Nil,
  #token_type => String | Nil,
  #expires_in => Integer | Nil,
  #refresh_token => String | Nil,
  #scope => String | Nil,
  #id_token_claims => Dictionary | Nil,
  #id_token => String | Nil
}

class tokenSetFrom: toks :: TokenResponse obtainedAt: sentAt :: Integer -> TokenSet =>
  #{#access_token => accessToken, #token_type => tokenType, #expires_in => expiresIn, #refresh_token => refreshToken, #scope => scope, #id_token_claims => claims, #id_token => idToken} := toks
  // ... builds the TokenSet from the bound names

Where the forms did not fit, the adopters kept the older code: a map pattern required every listed key, so API nodes with optional keys kept at:ifAbsent: (now covered by optional keys, ADR 0155); a match: arm is a single expression, so a multi-statement arm becomes a helper method; and an isError ifTrue: [^x] guard stays when matching would nest the happy path.


Live Patching

Hot code reload via message sends — no dedicated patch syntax needed.

// Canonical Counter (already running in the workspace)
Actor subclass: Counter
  state: value = 0
  increment => self.value := self.value + 1
  getValue => self.value

// Replace a single method — existing instances pick it up immediately
Counter >> increment =>
  Telemetry log: "incrementing"
  self.value := self.value + 1

// Redefine the class to add state — new instances get the updated shape
Actor subclass: Counter
  state: value = 0
  state: lastModified = nil
  increment =>
    self.value := self.value + 1
    self.lastModified := DateTime now
  getValue => self.value

Live patching works on the class side too (ADR 0084): ClassName class >> sel => body installs or replaces a class method on a registered class, and class-side dispatch resolves the new method immediately.

Object subclass: Registry
  class current => nil

// Live-edit the class method — subsequent class-side sends pick it up
Registry class >> current => "live"
Registry current        // => "live"

// Add a brand-new class-side selector
Registry class >> reset => 0
Registry reset          // => 0

The >> live-edit path recompiles the class's recorded source, so it applies to classes defined in source (inline Object subclass: or files loaded with Workspace load:). Purely-programmatic ClassBuilder classes have no recorded source; supply their class methods up front via classMethods: / addClassMethod:body: instead.

Typed sends and reload. A send whose receiver has a static type naming a Value or Object class, sealed or open (p :: Point, or self inside Point's own methods), compiles to a guarded direct call: when the receiver's class tag is exactly Point it calls Point's compiled module, and any other receiver (a subclass instance, or a value the annotation lied about) takes the ordinary dynamic send. A built-in receiver with its own representation (n :: Integer, xs :: List, d :: Dictionary, and likewise Float, Symbol, True, False, UndefinedObject, Block, Tuple, Reference, Port) compiles to a direct call guarded by the same representation test the dynamic send routes on (is_integer, is_list, a map with no class tag, …). String and Pid receivers do the same for every selector except the few the dynamic send answers outside their module, which stay dynamic: Pid's future protocol (await, whenResolved:, …) and the byte-level selectors String shares with Binary (byteAt:, asHex, …). The exact lists are the special_selectors of the String and Pid rows in the routing fixture (tagged_map_routing_conformance.json), which the runtime conformance tests check against beamtalk_primitive. A method added to String never moves any other selector: it is looked up inside String's module, so a typed call site sees it at once. Binary, Boolean, Bitstring and Character receivers, abstract classes, Object, Value, actors, and the supervisor and exception families always send dynamically. The result is always what a dynamic send answers (ADR 0025 amendment). Live patches (Point >> sel => …), removeSelector: and a reload into the same module all reach typed call sites at once, because they act inside that module. Two development-time operations do not until the calling code is recompiled, because the call site names the module the compiler saw:

Built-in receivers have no such caveat: a stdlib class can be neither removed nor redefined into another module, and a live patch of it acts inside its module's dispatch/3.

Saving live edits back to disk — compile:source:, ChangeLog, and flush (ADR 0082)

Live patches go into memory; they reach the .bt source file only when you flush. Between the patch and the flush, every in-memory mutation is recorded in the workspace ChangeLog — the pending-changes view, dirty-state tracker, and undo store rolled into one (ADR 0082).

The model has three layers: in-memory class state (hot-reloaded BEAM), the ChangeLog (per-workspace append-only log; persists across workspace restart), and the .bt files on disk. Every successful live patch updates memory and appends a ChangeEntry. Workspace flush walks pending entries and splices each patched body back into its source file via byte-span replacement — no AST re-print, no whole-file reformat — atomically (<file>.tmp + rename) with external-edit conflict detection.

The patcher primitives

MethodIntentLogs?Used by
aClass >> sel => body (parser sugar)durableyeshumans at the REPL
aClass compile: #sel source: "body"durableyesMCP save_method, browser "Save", REPL editor
aClass tryCompile: #sel source: "body"ephemeral (auto-prunes)yesMCP try_method, agent spikes
Workspace newClass: source at: pathdurable, kind: #'new-class'yesMCP save_class and LSP beamtalk.saveClass (via the save-class op), browser "New File"

>> and compile:source: are equivalent in effect — both install the new method and append a durable ChangeEntry. The keyword form takes the body as a String value so tools (MCP, LSP, browser editors) don't have to escape quotes or multi-line bodies back into source. tryCompile:source: installs in memory like compile:source: but tags the entry as ephemeral — successful spikes are promoted by re-calling compile:source: with the same body. Every successful in-memory mutation logs unconditionally, including spikes and patches against stdlib / dependency classes (which are not flushable). The audit trail is exhaustive on purpose.

Canonical patch → changes → flush round trip

> Counter >> increment => self.value := self.value + 1
=> Counter                          // memory patched
> Workspace changes notEmpty
=> true
> Workspace changes dirtyMethods
=> #{#Counter => #{#increment}}     // per-class set of dirty selectors
> Workspace flush
=> _                                // FlushResult; quiet on success
> Workspace changes isEmpty
=> true                             // flushed entries drop out of the active view

Workspace changes returns a ChangeLog object (see below). Workspace flush returns a FlushResult summary with #flushed, #files, #newClasses, #removedClasses, #skipped, and #conflicts. A non-empty #conflicts list means the listed entries remain pending and require manual reconciliation; a non-empty #skipped list means a pending destructive (Tier 2) entry was withheld — see Destructive flush below.

Targeted flush

Workspace flush                                   // every durable + flushable entry
Workspace flush: Counter                          // entries targeting one class
Workspace flush: #'new-class'                     // entries of one kind
Workspace flush: #{ #file => "src/counter.bt" }   // entries against one file
Workspace changes flushKinds: #{#agent}           // only agent-authored entries
Workspace changes flushKinds: #{#agent, #'new-class'}  // both filters AND together

External-edit conflict — patch, edit on disk, flush

> Counter >> increment => self.value := self.value + 2   // memory patched
=> Counter
// ... another editor (or `git pull`) modifies examples/counter.bt on disk ...
> Workspace flush
=> _   // FlushResult with #conflicts: [#{#file => "examples/counter.bt",
       //                                  #reason => #external_edit, ...}]
       // The patch stays pending; memory is still ahead of disk.

When flush detects an external edit, the offending entries stay in the log and the user picks the recovery path:

Workspace changes clear                           // drop the pending ChangeLog entries
                                                  //   (already-installed patches stay in memory
                                                  //    until workspace restart — use `revert:` to
                                                  //    actually re-install the prior method body)
Workspace changes revert: anEntry                 // undo one patch (re-install prior body)
// or open the file, reconcile by hand, then:
Workspace flush                                   // retry once disk matches expectations

Ephemeral spike → promote → flush

> Counter tryCompile: #doubled source: "doubled => self.value * 2"
=> Counter                          // memory patched, ChangeEntry logged as ephemeral
> (Counter spawn) doubled
=> 0                                // works — agent decides to keep it
> Counter compile: #doubled source: "doubled => self.value * 2"
=> Counter                          // promoted: durable ChangeEntry layered on top
> Workspace flush
=> _                                // disk gains the new method

The earlier ephemeral entry remains in the log for audit and is auto-pruned on the next workspace restart.

Creating a brand-new class file

> Workspace newClass: "Object subclass: Greeter\n  greet => ""hello""" at: "src/greeter.bt"
=> [Greeter]                        // compiled and installed in memory
> Workspace flush
=> _                                // writes src/greeter.bt

newClass:at: raises a loud, specific error (no silent fallback) if path already exists, lies outside the project tree, the declared class name does not match the path basename (ADR 0040 one-class-per-file convention), or a class of that name is already loaded.

Removing methods — removeSelector: and removeSelector:ifAbsent: (ADR 0112)

removeSelector: completes Behaviour's patch/create/remove trio alongside compile:source: and newClass:at:: it drops a method from the receiver's own method table (instance-side) or the receiver's metaclass's method table (class-side), then logs a durable kind: #'remove-method' ChangeEntry — exactly the ChangeLog participation a patch gets, just deleting text instead of replacing it.

sealed removeSelector: aSelector :: Symbol -> Behaviour
sealed removeSelector: aSelector :: Symbol ifAbsent: absentBlock :: Block(T) -> Behaviour | T
Counter removeSelector: #increment          // instance-side: touches instance_methods
Counter class removeSelector: #ofSize:      // class-side: touches class_methods

Receiver side follows the existing Counter vs Counter class convention already used to pick a side for live >> definitions — there is no boolean parameter. Both forms return the receiver (Behaviour) on success, so removals chain the same way patches do: Counter removeSelector: #a; removeSelector: #b.

Because dispatch always walks the class chain live (ADR 0032 — no flattened method-table cache), removing an overriding method instantly re-exposes whatever the superclass defines, with no restart and no cache to invalidate:

Actor >> initialize => Transcript show: 'base init'
Actor subclass: Counter
  state: value = 0

  initialize => Transcript show: 'counter init'

Counter new                    // prints 'counter init'
Counter removeSelector: #initialize
Counter new                    // prints 'base init' — no restart needed

removeSelector: removes a method defined on the receiving class itself, including one added by a live >> patch or folded in from a same-file >>; there is no separate extension layer to remove from (ADR 0152).

On the class side, removeSelector: also removes a runtime class-method fun (ADR 0084) installed with beamtalk_object_class:put_class_method/3,4. It checks the runtime fun first, then the compiled class method: the order dispatch resolves them. Removing the fun gives the selector back what it had before the first fun replaced it: the class's compiled method, or nothing, so the send falls through to an inherited method or does_not_understand. A static send compiled while the fun was installed takes the restored method on its next call. X class includesSelector: #sel answers true while such a fun is installed (BT-4438):

%% Erlang side: hot-patch a class method, then take the patch back.
ok = beamtalk_object_class:put_class_method(Pid, answer, fun(_ClassSelf) -> patched end).
Counter answer                          // => #patched
Counter class removeSelector: #answer
Counter answer                          // the compiled method's answer again

The bare form raises; removeSelector:ifAbsent: is the paired escape hatch — mirroring Dictionary>>at:ifAbsent: and Pharo's own removeSelector:/removeSelector:ifAbsent: pairing. A selector that is absent locally — never defined, already removed, or only inherited — raises a structured error with kind selector_not_found, deliberately distinct from does_not_understand (the message removeSelector: itself was understood and executed; only its argument had nothing to act on):

[Counter removeSelector: #bogus] on: Error do: [:e | e kind]
// => selector_not_found

Counter removeSelector: #bogus ifAbsent: ["not found"]
// => "not found"

// #printString is inherited from Object, not local to Counter, so it still
// raises — includesSelector: distinguishes "responds to" from "defines locally".
Counter includesSelector: #printString    // => false
Counter removeSelector: #printString      // raises selector_not_found

removeSelector:ifAbsent:'s block runs only on absence and its value is returned instead of the receiver.

Process semantics note. Like every Behaviour tower primitive, removeSelector:ifAbsent: runs in the caller's process (the Class → Behaviour chain-walk fallthrough), not the receiver class's gen_server. The absentBlock messaging the receiver class back is an ordinary cross-process send — no dispatch_error restriction applies here (unlike a block argument received by a locally-defined class method of a class that keeps its class process; see Passing Blocks Through Class Methods).

removeSelector: never refuses based on where a class lives — it always installs the removal in memory. What varies is whether the resulting ChangeEntry is flushable, exactly mirroring compile:source:'s rule (see Flushability below) rather than removeFromSystem's outright block (see removeFromSystem):

Integer removeSelector: #printString      // installs in memory, no error
Workspace changes dirtyMethods             // => #{#Integer => #{#printString}}
Workspace flush                            // skips it: not flushable (stdlib)

See ADR 0112 for the full design, including dangling-sender risk, and the side field's role in the ChangeLog schema.

autoflush

For users who want write-through editor semantics, flip a single workspace setting:

Workspace autoflush       // => false  (default)
Workspace autoflush: true // => true   (every successful durable patch flushes immediately)

Autoflush persists across workspace restarts. It is best-effort, not transactional — a flush failure under autoflush (external-edit conflict, write error) leaves memory ahead of disk and the entry pending in the log. The BEAM module install is not rolled back because live actors may hold references to the new closures. The error surfaces with a "memory ahead of disk" warning.

Ephemeral patches via tryCompile:source: are never autoflushed.

Flushability — what flush writes

A class is flushable iff its sourceFile is non-nil and lies inside the current project's source tree. Workspace flush writes only entries where intent = durable AND flushable = true. Other entries are reported under #conflicts (for external-edit / target-exists errors) or simply skipped:

ChangeLog

Workspace changes returns a ChangeLog object (analogous to Pharo's Smalltalk changes). All pending-state queries live on this object, not on the Workspace facade itself.

MethodReturnsDescription
sizeIntegerActive (live, re-appliable) entries
isEmpty / notEmptyBoolean"Is anything dirty?" is Workspace changes notEmpty
do: blockNilIterate active entries
select: blockListFilter all entries (reaches orphans, prior-epoch, and shadowed entries too)
dirtyMethodsDictionary#{Class => Set(selectors)} for the active set
revert: anEntryclassRe-install prev_source for that entry (itself a durable patch)
clearChangeLogDiscard every pending entry without writing to disk (memory keeps the patches until restart)
flushKinds: kindsFlushResultFlush only entries matching a Set of #instance / #class / #'new-class' / #'remove-method' / #'remove-class' / #'rename-class' / #'rename-method' / #'class-def' / #human / #agent symbols (both dimensions AND together)
allEntriesList(ChangeEntry)Every logged entry, including prior-epoch, orphan, shadowed, and clean entries
activeEntriesList(ChangeEntry)The default view: current-epoch, non-orphaned entries, collapsed to the latest entry per (class, selector) and filtered to those still differing from disk — one row per method that has a net change

Each ChangeEntry carries the patch's body, prior body, byte span, class, selector, intent (durable / ephemeral), flushable flag, authorKind (#human / #agent), and source-file reference. Bodies are stored as plain .bt files under <workspace>/changes/sources/; metadata lives in <workspace>/changes/changes.jsonl. cat, less, diff, and bt fmt all work on the source files directly.

Repeated patches to one method — or a patch followed by a revert:, which is itself a patch (ADR 0082 "Undo") — append multiple entries for the same (class, selector). The default view keeps only the latest (the one Workspace flush would apply) and marks the rest shadowed; e isShadowed identifies them, and select: still reaches them for audit.

The latest entry is also compared against the current on-disk body: if it matches (the method was reverted back to its on-disk state) the entry is clean (e isClean) and drops out of the default view — there is no net change to flush. Each entry that does differ carries e diff, the net on-disk→in-memory unified diff (lines prefixed / - / + ). So Workspace changes answers "what differs from disk", not "everything I touched this session"; the audit trail of every entry stays in allEntries / select:.

The ChangeLog persists across workspace restart. On restart, the workspace assigns a fresh epoch and excludes prior-epoch entries from the active view (their memory state is gone). The underlying audit log keeps them; reach them via Workspace changes select: [:e | e isOrphan].

REPL and tooling shortcuts

Every operation above is reachable via the REPL meta-commands, MCP tools, LSP executeCommand handlers, and browser actions. These are all thin front-ends over the Beamtalk language — see REPL shortcuts below and the Tooling guide for the surface tables.

Live Re-Checking on Reload (ADR 0105)

A live edit doesn't just change the class being patched — it can invalidate every existing caller in the image. Every save above (>>, class-body redefinition, Workspace load:) triggers an incremental re-check of known dependents: the compiler re-checks the callers beamtalk_xref (ADR 0087) already knows about, using the same type checker that runs at compile time, and publishes what it finds as live diagnostics — no rebuild, no manual "find senders" required.

Workspace load: "counter.bt"
counter := Counter spawn
counter getCount + 1          // => 1

// ... change `getCount -> Integer` to `getCount -> String`, save
// (a plain `Counter >> getCount -> String => ...` live patch) ...

⚠ reload check: Counter>>getCount signature changed;
   2 callers re-checked, 1 stale
   Dashboard>>refresh (dashboard.bt:14): `+` expects a number, `getCount` now returns String

Only genuinely-affected callers surface. If StatsView>>render also calls getCount but only stringifies the result, it re-checks clean against the new signature and stays silent — the header's "2 re-checked, 1 stale" is its only trace.

A removed selector is a does_not_understand waiting to happen, reported at Hint severity (ADR 0100 Rule 1 — a single closed-complete receiver):

ℹ reload check: Counter>>reset was removed; 1 caller remains
   AdminPanel>>onClick (admin.bt:9): `counter reset` will raise
   does_not_understand at runtime
   (Hint severity per ADR 0100 Rule 1 — single closed receiver)

A state:/field: slot added, removed, or retyped re-checks spawnWith: call sites and the changed slots' generated accessors the same way, under a shape_change classification.

Advisory, never blocking. The reload already happened — a finding informs, it never vetoes. Findings are workspace-session state (LSP diagnostics, REPL/workspace-UI notices), never persisted, and never fail a build; they disappear on workspace restart. Clearing is by replacement: every re-check of a caller replaces all of its findings attributed to that changed class with the fresh result — clean or different — so back-to-back reloads of the same method never leave a stale finding sitting alongside a current one (supersession), and a later reload that fixes the callee clears the caller's finding with no edit to the caller at all.

Two related, on-demand operations round out the surface:

(Counter precheckCompile: #getCount source: "getCount -> String => self.value printString")
// => a Dictionary shaped like the reload_check report — findings without installing

Workspace recheckImage
// => _  (checked/stale summary across the whole live image)

The dependent lookup is keyed by selector and the receiver's inferred type (ADR 0115): a candidate sender is dropped before it is ever re-checked when its recorded receiver type could not dispatch to the changed class — an unrelated class hierarchy, a protocol the changed class does not conform to, or the wrong side (a Counter class receiver is a dependent of a change to Counter's class-side methods, never its instance-side ones).

Narrowing is permissive by construction: a send the compiler could not type (dynamic), a send indexed by the runtime live-patch path (which has no type-checker access and records dynamic unconditionally), a row compiled before ADR 0115, and a receiver type that resolves to no loaded class or protocol are all kept as candidates. Those still re-check and let the checker's own type inference decide relevance — a size sender on an unrelated class simply re-checks clean. Fan-out is capped per reload (with a "N more not checked" note), now as a backstop over the narrowed pool rather than over every syntactic sender of the selector; one level of fan-out only, not transitive; and proxy-routed calls (ADR 0104 §4 forwarding) are invisible to xref, so a proxy-wrapped caller can go unflagged — see ADR 0105 and ADR 0115 for the full mechanism, severity rules, and accepted gaps.

Shape Versioning (ADR 0123)

Reload's structural fallback (add a defaulted field, drop a removed one, matching by name) handles additive changes for free — it always has. What it cannot express is a rename, a retype, or a field derived from others: dropping one field and adding another loses data instead of transforming it. shapeVersion: and migrateFromVN: are the two additions that let a class author say, in ordinary Beamtalk, how a live instance's state gets from one shape to the next — the same problem hot reload, persistence, and cross-node distribution all share, solved once.

shapeVersion: — declaring a version

A class declares its shape version with a class-header clause, on its own line before any state:/field: lines — the same position handleScope: occupies:

Actor subclass: Cart
  shapeVersion: 2
  state: items :: List = #()
  state: total :: Integer = 0
Cart shapeVersion
// => 2

Counter shapeVersion    // no shapeVersion: clause declared
// => 1

class migrateFromVN: — one method per step

A migration from shape N to shape N+1 is a class-side method, migrateFromVN:, taking the old fields as a Dictionary and returning the new fields as a Dictionary:

Actor subclass: Cart
  shapeVersion: 2
  state: items :: List = #()
  state: total :: Integer = 0

  /// v1 had only `items`; v2 caches their sum.
  class migrateFromV1: old :: Dictionary -> Dictionary =>
    old at: #total put: (old at: #items) sum

A rename the structural fallback cannot express (it would drop owner and default ownerName instead of carrying the value across):

Actor subclass: Account
  shapeVersion: 3
  state: balance :: Integer = 0
  state: ownerName :: String = ""

  class migrateFromV2: old :: Dictionary -> Dictionary =>
    (old at: #ownerName put: (old at: #owner)) removeKey: #owner

A Value, retyping a field (integer cents → float amount) and adding one:

Value subclass: Money
  shapeVersion: 2
  field: amount :: Float = 0.0
  field: currency :: Symbol = #USD

  class migrateFromV1: old :: Dictionary -> Dictionary =>
    (old at: #amount put: (old at: #cents) / 100.0) removeKey: #cents

Rules, all checked statically:

Ordinary sends are allowed inside a hook, so a migration is not pure — it just needs no process context (no live instance), which is what makes it callable standalone at the REPL, before any instance depends on it:

Cart migrateFromV1: #{#items => #(3, 4)}
// => #{#items => #(3, 4), #total => 7}

Cart migrateShape: #{#items => #(3, 4)} from: 1     // whole chain + reconcile
// => #{#items => #(3, 4), #total => 7}

migrateShape:from: (sealed, Behaviour >> migrateShape:from:) runs the full chain from a given version to the class's current shapeVersion, then reconciles against the declared fields — the identical operation a reload performs, exposed for standalone testing. It is idempotent at the current version (migrateShape:from: with aVersion = shapeVersion runs reconcile only, unchanged):

Cart migrateShape: #{#items => #(3, 4), #total => 7} from: 2
// => #{#items => #(3, 4), #total => 7}     // already current — unchanged

Chain and reconcile semantics

For a reload (or any migrateShape:from: call) from version V to the class's current T:

  1. For each K in V, V+1, …, T-1: if a migrateFromVK: exists, apply it to the running dictionary; otherwise that step is a no-op.
  2. Reconcile against the declared field list (the flattened one, inherited fields included). A declared field present in the dictionary is kept, whether or not it is late (see late Slots); absent gets its declared default; absent with no default is nil on an untyped class and a failure on a typed one (a migration may not leave a typed slot unset, same rule ADR 0078 enforces after initialize) — except a declared-but-absent late field (ADR 0124 §8), which is never defaulted or failed: it simply stays absent from the reconciled dictionary, on both a typed and an untyped class (late slots declare no default in the first place, so this check runs before the has-default/typed-no-default rules above, not as a fallback from them). An undeclared key is dropped with a warning.
  3. Downgrading (T < V) runs reconcile only — migrateToVN: downgrade hooks are reserved, not defined.

Changing a slot between eager and late (or back) is a shape change — it changes what an absent key means to the reconcile step above — and bumps shapeVersion: the same way adding, removing, or retyping a slot does; the reload-time tooling findings (ADR 0123 §4) flag a flip that lands without a version bump the same way they flag a dropped or retyped field.

Every live actor's state map carries one internal key, '__shape_version__', written by init/1 (absent means 1) and updated to the class's current version on a successful migration — never visible through fieldNames, printString, the Inspector, or any other reflection surface, exactly like every other internal key.

Suspend on failure, not resume-on-old-state or kill

If a migrateFromVN: hook raises, the actor is left suspended — not resumed with its old-shaped state under the new code (which is what the structural-only fallback used to do), and not killed:

Cart reload
// => Cart
⛔ reload: 1 instance of Cart left suspended — migrateFromV1: raised
   does_not_understand: List>>summ (Cart class >> migrateFromV1:, cart.bt:9)
   state intact at v1; fix the hook and `Cart reload` again, or stop the instances via `Node current actors`

The suspended instance's state is intact and inspectable — but not through an ordinary message send: anActor inspect (see Navigable Inspector) is itself a send, so it lands in the actor's mailbox like any other and cannot be answered while suspended. sys:get_state/sys:get_status are OTP debug messages, not gen_server calls — they bypass the mailbox entirely, which is what makes a suspended actor's state genuinely readable (via the Erlang FFI gateway, or external tools — observer, recon). Fixing the hook and reloading again re-suspends idempotently and, on success, resumes the actor at the new shape:

Cart reload            // migrateFromV1: still raises
// => Cart
Erlang maps get: #items from: (Erlang sys get_state: cart pid)
// => #(3, 4)     // state survives, still v1-shaped — an ordinary send to
                   // `cart` would time out instead; `sys:get_state` bypasses
                   // the mailbox

// ... fix the hook, save ...

Cart reload             // migrateFromV1: now succeeds
// => Cart
cart getTotal            // now answers on the new shape
// => 7

A synchronous caller blocked on the suspended actor simply times out with the usual structured timeout error until the author fixes the hook (or kills the instance) — the actor never silently continues on a wrong-shaped map, and nothing is lost in the meantime. See ADR 0123 for the full design, including the runtime-only versioned envelope (pack/1/unpack/1) that the persistence and distribution ADRs will consume — not yet exposed as a Beamtalk-callable method — and the reload-time tooling findings (§4).


Same-File Extension Methods (>>)

The >> syntax defines a method on a class from outside its body (ADR 0066, narrowed by ADR 0152). It is valid only where the class's source is at hand: in the file that defines the class, or as a live edit at the REPL or from the IDE / MCP (save_method, Class compile:source:). A >> definition in a file that does not define its target class is a compile error; see Cross-file extensions were removed below.

A method body, in a class or an extension, sees only self, its parameters, its own locals and true/false/nil. Top-level bindings and REPL variables are not visible inside it: pass them as arguments or store them in a field (BT-4665).

// point.bt — Pt is defined in this file
Value subclass: Pt
  field: x :: Integer = 0

  getX => self.x

// Instance method
Pt >> isZero => self.x =:= 0

// Class-side method
Pt class >> make => Pt x: 9

// Keyword method with typed parameter
Pt >> extra: n :: Integer => self.x + n

// Binary method
Pt >> + other :: Pt => Pt x: self.x + other getX

Type annotations on extensions

Same-file extensions support the same -> ReturnType annotation as regular methods. Additionally, extensions accept :: -> ReturnType as a visual separator between the selector and return type — especially useful on unary methods where there are no parameters to carry :: annotations.

// Standard return type syntax (same as inside a class)
Pt >> doubled -> Pt => Pt x: self.x * 2

// Extension-style: `:: ->` separates selector from return type
Pt >> negated :: -> Pt => Pt x: 0 - self.x

// Typed parameters with :: -> return type
Pt >> shiftBy: n :: Integer :: -> Pt => Pt x: self.x + n

Both forms are equivalent — the return type flows to the type checker identically. The :: -> form is preferred for unary extensions; the -> form is preferred when parameters already have :: annotations (to avoid consecutive :: tokens).

One file is one compilation unit for its class

An extension written in the target class's own file (Pt >> extra: n => ... or Pt class >> make => ... next to Value subclass: Pt) is part of Pt. The compiler folds it into the class before analysis and codegen, in beamtalk build, run, test and the REPL alike. A folded method is an ordinary method of the class: it gets a dispatch arm, static and direct calls, type checking and reflection, and it is not treated as an extension by browse or LSP grouping.

Cross-file extensions were removed (ADR 0152)

A Class >> selector => ... or Class class >> selector => ... in a file that does not define Class (including another file of the same package, and pkg@Class >> ...) is a compile error:

error: `String >> shout` adds a method to String, which is not defined in this file.
  = cross-file extension methods were removed (ADR 0152).

There is no deprecation period. What stays: a >> in the file that defines the class (above), a live Foo >> sel => ... / Foo class >> sel => ... at the REPL, IDE / MCP save_method and Class compile:source:, and the Foo >> #sel reflection operator, which answers a CompiledMethod and is not a definition.

Lookup is therefore closed: the receiver's compiled method, then each ancestor's compiled method (on the class side, the class methods; ADR 0084 runtime class-method funs count as the class's own methods), then doesNotUnderstand:args:. There is no extension step on either side, so loading a package cannot change which method answers a send to an existing class.

Migration:

See ADR 0152 for the full design and migration table.


Workspace and Reflection API

Beamtalk exposes system reflection and workspace operations as typed message sends to class-side facades (ADR 0040, ADR 0129). Beamtalk, Workspace, Transcript and SystemNavigation are ordinary sealed, stateless classes: every operation is a class sealed method sent to the class itself, there is no instance to construct, and Beamtalk new (etc.) is a compile error. They are not injected names, so they resolve exactly like Integer does and mean the same thing in the REPL, beamtalk run, beamtalk test and releases. There is no current, default or singleton accessor to call first.

FacadePurposeNeeds a workspace?
BeamtalkClass registry, help, release reflectionNo
WorkspaceLoading, testing, bindings, flush/change logYes (except isAvailable)
TranscriptREPL shared log; day-0 output convenienceOnly recent / clear
SystemNavigationCross-class code queriesNo

Facts about the BEAM node or the running program are on Node and Program, and logging control is on Logger; none of these are on Beamtalk.

Beamtalk — System reflection

Provides access to the class registry, documentation and release provenance. Analogous to Smalltalk's Smalltalk global. Works everywhere, with no workspace.

MethodReturnsDescription
versionStringBeamtalk version string
allClassesList(Class)All registered classes (class objects)
classNamed: #NameClass or nilLook up a class by name
help: aClassStringClass documentation: name, superclass, method signatures. Accepts a class, a Symbol or a String
help: aClass selector: #selStringDocumentation for a specific method
erlangHelp: "module"StringType signatures and EEP-48 docs for an Erlang module
erlangHelp: "module" selector: #funStringDocumentation for one function of an Erlang module
releaseInfoDictionaryThis node's release provenance; #{#release => nil} on a non-release node (never an error)
shapeManifestDictionaryclassName -> #{#version, #fields, #migrations} for every registered project class (ADR 0125 §3.4)
Beamtalk version
// => "0.6.0"

Beamtalk allClasses includes: Integer
// => true

Beamtalk classNamed: #Counter
// => Counter (or nil if not loaded)

Beamtalk help: Integer
// => "== Integer < Number ==\n..."

Beamtalk help: Integer selector: #+
// => "Integer >> +\n..."

Beamtalk has no namespace-snapshot accessor. Use Beamtalk classNamed: / Beamtalk allClasses for the class registry, or SystemNavigation for queries over it.

Logging and debug control are on Logger, not Beamtalk (ADR 0129 §3, BT-3653). The selectors are unchanged and, like Logger info:, need no workspace:

MethodReturnsDescription
Logger logLevel / Logger logLevel: levelLogLevel | #all | #none / NilRead / set the OTP primary log level
Logger logFormat / Logger logFormat: formatLogFormat / NilRead / set the log output format
Logger debugTargetsList(Symbol)Debug targets available to enable
Logger enableDebug: target / Logger disableDebug: targetNilTurn debug logging on or off for a target
Logger activeDebugTargetsList(Symbol)Targets with debug logging currently on
Logger disableAllDebugNilTurn all debug logging off

Workspace — Project operations

Provides file loading, testing, bindings and the flush/change-log loop. Scoped to the running workspace: every selector raises a structured no_workspace error where no workspace runs (e.g. beamtalk test); Workspace isAvailable asks without raising. It works under beamtalk run, workspace and release modes.

Facts about the BEAM node or the running program are not on Workspace (ADR 0129 amendment): node introspection lives on Node and the root supervisor on Program rootSupervisor.

MethodReturnsDescription
isAvailableBooleanTrue iff a workspace is running on this node. Never raises
load: "path"List(Behaviour) or ErrorCompile and load one .bt file; a directory raises eisdir (use sync for a project)
newClass: source at: pathList(Behaviour)Create a brand-new class from source at path; logs a kind: #'new-class' ChangeEntry (ADR 0082)
moveClass: AClass to: "path"BehaviourMove a class's declaration to another file (ADR 0114)
classesList(Behaviour)All loaded user classes (those with a recorded source file)
testClassesList(Behaviour)Loaded classes that inherit from TestCase
bindingsBindingsViewLive, write-through view of the bind:as: entries (see Sessions and binding layers)
bind: value as: #NameNilRegister a value under a name for REPL evals. Refuses any registered class name (name_conflict)
unbind: #NameNilRemove a registered name; raises if it is not found
currentSessionSession or nilThe calling process's REPL session (same value as Session current); nil outside a REPL eval
sessionsList(Session)All live REPL sessions as Session values
syncDictionaryIncrementally compile the project's changed files (:sync)
recheckImageDictionaryWhole-image type re-check, with checked / stale / findings (ADR 0105)
testTestResultRun all loaded test classes
test: AClassTestResultRun a specific test class
changesChangeLogPending in-memory changes (ADR 0082) — see Saving live edits back to disk
flushDictionaryWrite every durable + flushable ChangeEntry back to its source file (ADR 0082)
flush: filterDictionaryFlush a subset (Class / Symbol kind / #{#file => path})
flush: filter confirmDestructive: boolDictionaryFlush a subset, confirming destructive entries (ADR 0113)
flushIncludingDestructiveDictionaryFlush including destructive entries (ADR 0113)
autoflushBooleanWorkspace setting (default false); persists across restarts
autoflush: enabledBooleanToggle write-through: every durable patch immediately flushes (best-effort)
startSupervisor: AClass / stopSupervisor: AClassSupervisor / NilAttach / stop a supervisor under the workspace supervisor
dependenciesDictionary(String, Package)Direct dependency packages of the workspace
Workspace isAvailable
// => true  (false under `beamtalk test`, where every other selector raises no_workspace)

Workspace load: "examples/counter.bt"
// => #(Counter)  (Counter is now registered)

Workspace classes includes: Counter
// => true

Workspace testClasses includes: CounterTest
// => true

(Workspace test: CounterTest) failed
// => 0  (all tests pass)

Node current actors unwrap size
// => 3  (number of live actors; see Node introspection below)

Transcript — The REPL's shared log

Transcript is a sealed, stateless class-side facade (ADR 0129 §5). It has no instance, no stream protocol and no capture API. Its behaviour depends on whether an interactive workspace is running:

SelectorIn an interactive workspaceElsewhere (run, test, releases)
show: valueAppends the value's text to the workspace transcriptOne Logger notice event, domain [beamtalk, user, transcript]
crAppends a newlineNo-op
showCr: valueshow: then crOne Logger event
recentThe buffered lines (List(String))Raises no_workspace
clearEmpties the bufferRaises no_workspace
Transcript showCr: "Hello"
Transcript show: "a"; cr; show: "b"
Transcript recent

Outside a workspace the Logger route prints plain text, one line per event, so two consecutive show: sends are two events, not one line, and ordering relative to Console (which writes synchronously) is not guaranteed. Silencing or redirecting the output is ordinary Logger configuration on the transcript domain.

Guidance: Transcript exists for newcomers and REPL use. Programs should use Logger (structured logging, ADR 0064) for diagnostics and Console for plain stdout/stderr. The show: / showCr: convenience methods on Object delegate to Transcript. There is no showLine:; use showCr:.

Node introspection (ADR 0129 amendment)

Reads of node state are per-node queries on Node (ADR 0126), not Workspace selectors. Every one answers a Result on every receiver, including Node current, so a selector has one return type; a peer is reached via erpc and its failures come back as Error values (node_down, timeout, insecure_distribution, remote_code_mismatch), never raised. They work in every boot context, including beamtalk test.

MethodReturnsDescription
aNode actorsResult(List(Actor), Error)Every live actor on the node (runtime-owned actor registry)
aNode actorsOf: AClassResult(List(Actor), Error)Live actors of the class or a subclass
aNode actorAt: pidStrResult(Actor | Nil, Error)The live actor with that pid string, or nil
aNode processesResult(SupervisionTree, Error)The node's default-scope supervision tree (ADR 0092)
aNode supervisorsResult(List(Supervisor), Error)Root application supervisor plus workspace-attached ones
aNode shapeSkewResult(Integer, Error)Classes whose shape version differs from this node's (ADR 0126 §8)
Node connectedList(Node)Visible connected peers (replaces Workspace nodes)

aNode actors lists every live actor, whereas Actor allRegistered / Actor allRegisteredOn: aNode list only the name-registered ones (Actor named:). The root supervisor and the declared supervisor class are program/manifest facts:

Node current actors unwrap size          // every live actor on this node
Node current actorsOf: Counter           // => Result ok: #(...)
Node connected collect: [:n | n shapeSkew unwrap]
Program rootSupervisor                   // running application's root supervisor, or nil
(Package named: "my_app") supervisorClass  // declared [application] supervisor class, or nil

Class-based reload via Behaviour >> reload

Every class records the source file it was compiled from. You can reload a class directly via a message send — no file path needed:

MethodReturnsDescription
sourceFileString or nilPath the class was compiled from; nil for stdlib/dynamic classes
reloadselfRecompile from sourceFile, hot-swap BEAM module
Counter sourceFile
// => "examples/counter.bt"

Counter reload
// => Counter  (recompiled and hot-swapped)

Integer sourceFile
// => nil  (stdlib built-in, no source file)

Integer reload
// => Error: Integer has no source file — stdlib classes cannot be reloaded

Hot-swap semantics follow BEAM conventions: live actors running the old code continue their current message; the next dispatch uses the new code.

removeFromSystem — removing a whole class (BT-785, ADR 0113)

removeFromSystem tears a class down entirely: stops its live actors, stops the class gen_server, purges the BEAM module, and purges every derived registry (xref, protocol conformance, compiler cache, workspace source). Unlike removeSelector: (above), it is a hard, unconditional refusal for stdlib classes and classes with subclasses — there is no in-memory-but-non-flushable escape hatch.

It also refuses while any supervisor still holds a child of the class (a static child spec, a DynamicSupervisor child, or a child started through a withClassMethod: factory), including supervisors nested anywhere in a tree and a transient child that has exited normally but whose spec remains (BT-4936). The error names the supervisor and the child, and nothing is stopped or removed. Remove the child from the supervisor first (terminateChild: then deleteChild:), then remove the class. Unsupervised actors of the class are stopped as before.

Counter removeFromSystem   // => nil (Counter class removed; refuses if Counter has subclasses)
Integer removeFromSystem   // => Error: cannot remove stdlib class

A successful removal also logs a durable kind: #'remove-class' ChangeEntry (ADR 0113 Phase 1) — the same audit-trail-is-unconditional rule every other in-memory mutation follows. Flushing that entry deletes the class's .bt file, which is why it needs its own confirmation gesture — see Destructive flush — flushIncludingDestructive and confirmDestructive below.

For removing a single method while keeping the class, see removeSelector: / removeSelector:ifAbsent: above.

A pending (unflushed) #'remove-class' entry is revertable, same as any other ChangeLog entry: Workspace changes revert: anEntry recompiles and reinstalls the whole class from the entry's recorded prior source, reusing the same install path newClass:at: uses (ADR 0113 Phase 3). Before reinstalling, the runtime compares the current on-disk file against the entry's recorded prev_source_ref snapshot byte-for-byte; if the file was edited externally (another session, git, an editor) while the removal sat pending, revert: raises a structured error instead of silently discarding the external edit — the class stays removed and the original entry stays pending (BT-3213). Once flushed — the .bt file actually deleted — the entry is pruned from the active view and revert: has nothing left to act on; recovering a flushed removal is git's job. removeSelector:'s #'remove-method' entries are revertable the same way (they re-install the removed method's recorded prior body).

Renaming a class or method — renameTo:, renameSelector:to:, and moveClass:to: (ADR 0114)

renameTo: (class rename) and renameSelector:to: / renameSelector:to:ifAbsent: (method rename) give a class or method a new identity in place — unlike removeFromSystem + newClass:at:, which would lose instance identity, in-place undo, and any automatic reference fixing. Both compute their rewrite sites from the same xref infrastructure SystemNavigation exposes above (referencesTo:, sendersOf:, implementorsOf:) rather than a new query, follow removeSelector:'s established shape (sealed class-side methods, return the receiver for chaining, raise a structured #beamtalk_error{} — reusing removeSelector:'s selector_not_found kind — on an absent source, paired with an ifAbsent: escape hatch), and — like removeFromSystem — never touch disk on their own; the resulting entry needs its own confirmed destructive flush (below) to reach disk.

sealed renameTo: aNewName :: Symbol -> Behaviour
sealed renameSelector: aSelector :: Symbol to: aNewSelector :: Symbol -> Behaviour
sealed renameSelector: aSelector :: Symbol to: aNewSelector :: Symbol
    ifAbsent: absentBlock :: Block(T) -> Behaviour | T

Receiver and side, for renameSelector:to:, mirrors removeSelector:: Counter renameSelector: #a to: #b touches the instance-side table, Counter class renameSelector: #a to: #b touches the class-side table.

Counter renameTo: #Accumulator
Counter renameSelector: #increment to: #incrementBy
Counter class renameSelector: #ofSize: to: #withCapacity:

A collision with an existing name is refused, loudly, the same way removeFromSystem refuses a name it can't act on:

Counter renameTo: #Accumulator
// => Error: cannot rename Counter to Accumulator — Accumulator already exists

Counter renameSelector: #increment to: #decrement
// => Error: Counter already defines #decrement locally — refusing to overwrite

Counter renameSelector: #bogus to: #anything
// => Error: selector_not_found

Counter renameSelector: #bogus to: #anything ifAbsent: ["not found"]
// => "not found"

renameTo: rewrites every in-project reference it can find, immediately, in memory — constructor/message sends, type annotations (including generic parameters like List(Counter)), superclass declarations, and same-file >> declarations (via the union of referencesTo: and the class's direct subclasses). A class live-patched via >> since its last full compile is a real, accepted residual-risk gap here (referencesTo:'s reference-indexing channel is unconditionally empty for live patches), and a plain string/comment occurrence of a class's name is never rewritten — the same category of accepted risk removeSelector:'s dangling senders already carry, just concretely named.

renameSelector:to: auto-rewrites only structurally-safe self/super sends — not every textual sender sendersOf: finds. sendersOf: #sel returns every send of that selector name anywhere in the project, regardless of which class's implementation the sender actually meant to call — auto-rewriting all of them would risk silently corrupting unrelated, working code that happens to share a selector name. renameSelector:to: therefore splits the results into two tiers, reported on the resulting ChangeEntry:

candidate_sites is exactly removeSelector:'s dangling-sender risk made visible rather than silent: nothing there is rewritten or written by flush, but a caller inspecting the returned ChangeEntry (Workspace changes — below) sees both counts and can patch the review list manually via compile:source:, the same way any other live patch is made.

Workspace moveClass: aClass to: aNewPath relocates a class's .bt file without changing its name — the pure file-move counterpart to renameTo:, useful when only where a class lives on disk should change:

Workspace moveClass: Counter to: "src/math/counter.bt"

Refusal is decided per primitive, by whether the in-memory effect alone is safe against a class the project doesn't own the callers of:

PrimitiveStdlibDynamic (ClassBuilder)Dependency
renameTo:RefusesAllowed, not flushableRefuses
renameSelector:to:Allowed, not flushableAllowed, not flushableAllowed, not flushable

renameTo: refuses a stdlib or dependency class outright — the xref index only covers in-project source, so its site-discovery can never be complete for a class whose callers might live outside the project. renameSelector:to: reuses removeSelector:'s narrower granularity argument: a single-selector rename's blast radius (one stray un-rewritten self/super sender) is smaller than a whole class silently losing referential integrity project-wide, so it installs in memory unconditionally and only gates the disk write.

A successful rename logs a durable kind: #'rename-class' / #'rename-method' ChangeEntry — the same audit-trail-is-unconditional rule removeFromSystem follows — carrying the multi-file sites list flush will apply and (for rename-method) the candidate_sites review list above. Both kinds join removeFromSystem in Tier 2 (below): flushing rewrites every confirmed site across however many files it spans (a class rename also moves the .bt file itself), which is why it needs its own confirmation gesture. Unlike removeFromSystem, a pending rename entry is revertable — Workspace changes revert: anEntry splices every one of the entry's own recorded sites back to its own prior body, at its own recorded location, rather than re-running renameTo:/renameSelector:to: (which would re-compute site discovery against post-rename state and could disagree with what the original rename actually touched).

Destructive flush — flushIncludingDestructive and confirmDestructive (ADR 0113)

Every flushable ChangeEntry classifies into one of two tiers:

TierEntriesFile survives?Gate
1patches, newClass:at:, removeSelector: (#'remove-method')Yes — excising a recorded span leaves the file in place, mechanically identical to a patchNone — Workspace flush applies it directly
2removeFromSystem (#'remove-class'), renameTo: / Workspace moveClass:to: (#'rename-class'), renameSelector:to: (#'rename-method')No — a class removal deletes the .bt file; a rename rewrites one or more files (a class rename also moves the file itself)Explicit confirmDestructive

Workspace flush (no argument) applies only Tier 1. A pending Tier 2 entry is left pending and reported in the summary's #skipped field (#{#seq, #class, #reason => #destructive}), distinct from a conflict:

Counter removeFromSystem                          // memory step: unconditional, as above
Workspace flush
=> _   // FlushResult with #skipped: [#{#reason => #destructive, ...}]
       // Counter.bt is untouched; the removal stays pending.

Reaching Tier 2 always requires an explicit gesture — never a workspace setting or environment variable:

Workspace flushIncludingDestructive               // unscoped: applies every pending
                                                    //   Tier 1 + Tier 2 entry
Workspace flush: Counter confirmDestructive: true  // scoped to one class
Workspace changes flushKinds: #( #'remove-class' ) confirmDestructive: true
                                                    // scoped to one kind

flushIncludingDestructive is a bare unary selector rather than a keyword message — once the call is unscoped there is no class/kind/file argument left to attach a confirmDestructive: keyword to. The scoped two-keyword forms (flush:confirmDestructive:, flushKinds:confirmDestructive:) compose confirmDestructive as one more independent filter dimension on top of the existing flush: / flushKinds: mechanisms, the same way flushKinds: already composes entry-kind and author-kind filters.

autoflush: true never implies confirmDestructive: true — Tier 1 still autoflushes immediately; a class removal always needs its own, separate confirmation regardless of the autoflush setting. Class-removal deletion is staged (same-filesystem rename, then unlink) so a crash between the two steps leaves a recoverable file, never a partial or silent loss; a re-flush finishes the delete. See ADR 0113 for the full design, including the external-edit conflict table and delete atomicity — and ADR 0114 for how renameTo:/renameSelector:to: extend this same tier and gate to genuinely multi-file staging.

Editor integration (LSP): flush uses typed workspace/applyEdit resource operations for structural file changes: a Workspace newClass:at: flush emits a CreateFile operation (BT-3212), and a remove-class Tier 2 destructive flush emits a DeleteFile operation (BT-3209), so the editor can distinguish file creation and deletion from ordinary content edits. Both fire regardless of whether the file was open in the editor. A rename-method flush emits a TextDocumentEdit per confirmed site (BT-3275); a rename-class flush emits TextDocumentEdit for cross-file reference rewrites and a custom beamtalk-lsp/documentMoved notification ({oldUri, newUri}) for the moved declaration file — replacing the RenameFile op that silently no-ops in VS Code when the old path is already gone (BT-3285). Ordinary method patches continue to use the generic TextEdit shape, gated on the file being open.

Program — This running program (ADR 0099 §2)

Program names the running program in every execution context. Besides commandName and exit / exit:, Program package returns the program's root Package (Package named: <root package>), so a program can reach its own manifest facts without hard-coding its name:

Program package version

Every launcher records the root package as the beamtalk_runtime app-env key root_package from the Rust-parsed beamtalk.toml (beamtalk repl, beamtalk run script and service modes, beamtalk workspace create, the escript bootstrap; beamtalk release writes it into sys.config) and loads the package's .app. It never returns nil; it raises a structured error instead:

KindWhen
no_program_packageNo project (bare beamtalk repl)
ambiguous_program_packagebeamtalk test runs several packages at once (a single package under test is the root)
package_not_loadedThe root package's .app is not on the code path (run beamtalk build)

Package classes reads the classes list of the package's .app, which beamtalk build writes. A workspace sync (load-project, Workspace sync, :sync) refreshes that in-memory list from the live class registry, so a class added to the project's src/ appears in Package classes after the sync without a rebuild. A class defined only by evaluating source in the REPL is listed once it is synced from a file; the .app file on disk is only rewritten by beamtalk build.

Program exit: / System halt: (ADR 0099 §3, BT-3634)

Program exit: N triggers a graceful shutdown (init:stop(N)) when the program owns the node. System halt: N is an immediate stop that flushes Logger handlers first.

ContextProgram exit: NSystem halt: N
beamtalk run (script/service)Stops with exit status NImmediate halt with status N
Release foreground / evalStops with exit status NImmediate halt with status N
EscriptStops with exit status NImmediate halt with status N
Actor in a node-owning contextStops the node gracefullyImmediate halt
Workspace (actor send)Raises program_exit_outside_entryRaises unsupported
beamtalk testRaises #program_exit with statusRaises unsupported
Release console REPLEnds this session; the release node keeps runningAllowed (the release owns the node)

SystemNavigation — Cross-class code queries

SystemNavigation provides Smalltalk-style live-image queries over the loaded class registry. It is a stateless class-side facade (ADR 0129): every query is a class sealed method sent to the class itself — there is no instance to construct, and SystemNavigation new is a compile error. The class is a plain value, so nav := SystemNavigation and nav actorClasses work too.

MethodReturnsDescription
allClassesList(Behaviour)All registered classes (class objects)
actorClassesList(Behaviour)Classes whose superclass chain includes Actor, sorted alphabetically
dnuHandlersList(Behaviour)Classes that locally override doesNotUnderstand:args:, sorted alphabetically
implementorsOf: #selList(Behaviour)Classes that define the given selector
sendersOf: #selList(Dictionary)#{#class, #selector, #line} for every method body that sends #sel
messagesSentBy: aMethodList(Dictionary)#{#selector, #line} for every message send in aMethod's body — the outgoing-call dual of sendersOf:. aMethod must be a CompiledMethod (e.g. Counter >> #increment). Excludes Erlang FFI sends
referencesTo: aClassList(Dictionary)#{#class, #selector, #line} for every method body that references the class name
announcementsSentBy: aClassList(Behaviour)Distinct Announcement subclasses that aClass statically emits via announce: / announceAndWait: / announceAndWait:timeout:, sorted by name — the publisher-side dual of AnnouncementNavigation. Advisory: only constructor-call arguments (announce: (PriceChanged newPrice: 42)) resolve; Dynamic/indirect arguments are skipped
announcementSitesSentBy: aClassList(Dictionary)#{#class, #selector, #line, #announcementClass} for every resolvable announcement emission within aClass — the site-level form of announcementsSentBy:
ffiSitesFor: aSpecList(Dictionary)#{#class, #selector, #line} for every method body that calls Erlang module:function (optionally arity-qualified, e.g. "lists:reverse/1")
fieldReadersOf: #slot in: aClassList(Dictionary)#{#class, #selector, #line} for every method that reads field/class var #slot while scanning aClass + subclasses on instance and class sides
fieldWritersOf: #slot in: aClassList(Dictionary)#{#class, #selector, #line} for every method that writes field/class var #slot while scanning aClass + subclasses on instance and class sides
methodsMatching: aRegexList(Dictionary)#{#class, #selector} for every method whose source matches the regex
selectorsMatching: patternList(Symbol)Selectors matching a case-insensitive substring (e.g., "print")
selectorsForClass: aClassList(Symbol)All selectors defined on a class (instance + class)
classesInPackage: aPackageList(Behaviour)Class objects belonging to package aPackage (Symbol or String; ADR 0070)
subclassesOf: aClass in: aPackageList(Behaviour)Subclasses of aClass that live in package aPackage (allSubclasses filtered by package)
unimplementedSelectorsList(Dictionary)Selectors sent but defined nowhere — a typo-finder lint
unusedSelectorsList(Dictionary)Selectors defined but sent nowhere — dead-method candidates

Body-based queries (sendersOf:, referencesTo:, ffiSitesFor:, methodsMatching:, announcementsSentBy:, announcementSitesSentBy:, and the selector-lint queries) scan instance-side and class-side method bodies. fieldReadersOf:in: and fieldWritersOf:in: scan aClass + subclasses on instance/class sides. Each result's #class field is the class object for an instance-side hit and the metaclass object (Counter class) for a class-side hit.

announcementsSentBy: is a deliberately advisory static analysis of a dynamic language — the publisher-side dual of AnnouncementNavigation's runtime subscription queries. It resolves an announce: argument to its Announcement subclass only when the argument is a constructor call on a bare class reference (announce: (PriceChanged newPrice: 42) or announce: PriceChanged new). A Dynamic-typed or indirect argument (announce: someVar, perform:-style dispatch) is unresolvable by construction and is silently skipped, so the result is discoverability, never a sound or exhaustive emission contract.

nav := SystemNavigation

nav implementorsOf: #printString
// => [Object, Integer, String, ...]

nav sendersOf: #increment
// => [#{#class => CounterTest, #selector => #testIncrement, #line => 12}, ...]

nav referencesTo: Counter
// => [#{#class => CounterTest, #selector => #setUp, #line => 5}, ...]

nav methodsMatching: (Regex from: "printString") unwrap
// => [#{#class => Object, #selector => #printString}, ...]

nav selectorsMatching: "print"
// => [#printString, #printOn:, ...]

nav messagesSentBy: (Counter >> #increment)
// => [#{#selector => #+, #line => 2}, ...]

nav announcementsSentBy: PriceTracker
// => [PriceChanged, ...]  (distinct Announcement subclasses PriceTracker emits)

nav announcementSitesSentBy: PriceTracker
// => [#{#class => PriceTracker, #selector => #notify, #line => 4, #announcementClass => PriceChanged}, ...]

nav unimplementedSelectors
// => []  (empty = no typos in the loaded registry)

nav unusedSelectors
// => [#{#class => MyLib, #selector => #helperNoOneCalls}, ...]

nav actorClasses
// => [Actor, ClassBuilder, MyActor, ...]

nav dnuHandlers
// => [ErlangModule, ProtoObject, TimeoutProxy, ...]

nav classesInPackage: #stdlib
// => [Actor, Array, ...]

nav subclassesOf: Number in: #stdlib
// => [Float, Integer]

nav fieldReadersOf: #value in: Counter
// => [#{#class => Counter, #selector => #getValue, #line => 5}, ...]

nav fieldWritersOf: #value in: Counter
// => [#{#class => Counter, #selector => #increment, #line => 3}, ...]

nav ffiSitesFor: "lists:reverse"
// => [#{#class => MyList, #selector => #reversed, #line => 7}, ...]

Sessions and binding layers (ADR 0081)

A free identifier in a REPL expression (x, answer, Counter) resolves through three tiers, in this order:

TierOwnerSourceAccessor
1. Session localsthe session (per connection)x := 42 typed in the shellSession current bindings
2. Workspace bindingsthe workspace (shared)Workspace bind: v as: #name entriesWorkspace bindings
3. Class registrythe runtimeevery loaded class (Counter, Integer, Transcript, Beamtalk, Workspace)Beamtalk allClasses

An earlier tier shadows a later one: a local named answer hides a workspace binding of the same name, and Integer := 3 creates a session local that shadows the Integer class for that session. A name found in no tier raises undefined_variable.

Only tiers 1 and 2 are REPL-specific. Method bodies and batch-compiled code (a .bt file under beamtalk run, beamtalk test or a release) use only the class registry, so Transcript, Beamtalk, Workspace and SystemNavigation resolve there exactly as Integer does. They are classes, not entries in a binding layer, so Workspace bindings does not list them.

Session — a first-class session value

Session is a factory, mirroring Date today / Smalltalk current: two class-side methods return a session value you then message. There is no class-side operation mirror (no Session bindings). Workspace-wide bindings are workspace state, reached via Workspace bindings.

Class methodReturnsDescription
Session currentSession or nilThe calling process's session; nil outside a REPL eval (compiled code has no session)
Session withId: anIdSession or nilLook up a session by its protocol id; nil if unknown or no longer alive
Instance methodReturnsDescription
bindingsBindingsViewLive view of this session's locals (the x := 42 layer)
resolve: #nameObjectResolve a name the way bare-name lookup does (locals → workspace bindings → classes). Shares the one resolver with bare-name lookup, so it raises undefined_variable for a name that resolves nowhere — exactly as typing the bare name would
clearnilClear this session's locals (workspace bindings remain)
idStringStable session identifier (matches the protocol session id)
x := 42
// => 42

Session current bindings keys
// => #(#x)

Session current bindings at: #x
// => 42

Session current resolve: #Transcript
// => Transcript (the class, from the class registry)

Session current resolve: #notDefinedAnywhere
// => Error: Undefined variable: notDefinedAnywhere

Session current clear
// => nil

Outside a REPL eval (e.g. in a .bt file run via beamtalk run), Session current returns nil. Guard with ifNotNil: rather than a predicate:

Session current ifNotNil: [:s | s clear]

BindingsView — a live, write-through Dictionary view

Both Session current bindings and Workspace bindings return a BindingsView: a small Dictionary-protocol value (at:, at:put:, removeKey:, includesKey:, keys, values, size, do:) backed by live state. at:put: returns the value put; removeKey: returns nil.

// Session-local write — DEFERRED to end of eval, visible on the NEXT line:
Session current bindings at: #y put: 99
// => 99
y
// => 99

// Workspace-binding write — SYNCHRONOUS (routes through bind:as:),
// visible immediately on the next line:
Workspace bindings at: #answer put: 42
// => 42
answer
// => 42

One documented asymmetry under the shared type: session-local writes are deferred to the end of the current eval (the eval worker holds a state snapshot), so a same-expression read-back sees the old value; workspace-binding writes hit shared ETS immediately. bind:as: and Workspace bindings at:put: refuse to shadow any registered class name (name_conflict):

Workspace bindings at: #Workspace put: nil
// => Error: Workspace is a system name and cannot be shadowed

Cross-session access (read-only)

Session withId: returns another session by id — used by tooling (LSP, VS Code) to read the user's session from a separate completion session. Cross-session reads are allowed; writes raise cross_session_mutation_unsupported:

// Pick a session that is NOT this one — session ordering is not guaranteed, so
// `sessions first` could be the current session, where a write would succeed
// (self-session) rather than raise. Tooling normally already knows the target id.
myId    := Session current id
otherId := (Workspace sessions collect: [:s | s id]) detect: [:each | each /= myId]
other   := Session withId: otherId

other bindings keys          // => cross-session READ, allowed
other bindings at: #x put: 9 // => Error: Cannot mutate another session's bindings

REPL shortcuts (: commands) are thin wrappers

The REPL : commands are convenience aliases that desugar to the native message sends:

REPL shortcutBeamtalk native equivalent
:syncWorkspace sync
:unload Counter(removes the class; no single message-send form)
:testWorkspace test
:test CounterTestWorkspace test: CounterTest
:help CounterBeamtalk help: Counter
:help Counter incrementBeamtalk help: Counter selector: #increment
:changesWorkspace changes
:dirtyWorkspace changes dirtyMethods
:flushthe flush operation (same effect as Workspace flush)
:flush Counterthe flush operation scoped to a class (Workspace flush: Counter)
:flush #'new-class'the flush operation scoped to an entry kind (Workspace flush: #'new-class')
:flush #incrementthe flush operation scoped to a method selector (Workspace flush: #increment)
:flush Counter>>#incrementthe flush operation scoped to one method of one class
:flush #{ #file => "path" }the flush operation scoped to a file (Workspace flush: #{ #file => "path" })

The native forms work from compiled code, scripts, and actor methods — not just the REPL.


Actor Observability and Tracing (ADR 0069)

The Tracing class provides actor observability and performance telemetry. It is a sealed, class-only facade (like System and Logger) — all methods are class-side, there are no instances. See ADR 0069 for the full design. To emit your own application events, use Telemetry (Application Telemetry Events).

Two levels of instrumentation are available:

Tracing Lifecycle

// Enable detailed trace capture
Tracing enable
// => nil

// Check if tracing is active
Tracing isEnabled
// => true

// Disable trace capture (class aggregates continue;
// per-actor detail is dropped)
Tracing disable
// => nil

// Clear all trace events and aggregate stats
Tracing clear
// => nil

Aggregate Stats (Always-On)

Aggregate stats are collected for every actor dispatch, even when trace capture is disabled. They include call counts, total duration, min/max/average times, and error counts. Stats are keyed by class: one "class:<Class>" entry per class with per-method figures. While tracing is enabled, stats additionally holds one entry per pid with live actors' per-actor detail.

// All stats: class entries always, plus per-actor entries while enabled
Tracing stats
// => #{...}  (Dictionary keyed by "class:<Class>", and by pid while enabled)

// Stats for a specific actor (only collected while tracing is enabled;
// answers #{} when tracing is off)
Tracing statsFor: myCounter
// => #{...}

Trace Event Queries

When trace capture is enabled, individual call events are recorded to a ring buffer. These are available for querying even after the actor has stopped.

// All captured events (newest first)
Tracing traces
// => #(...)

// Events for a specific actor
Tracing tracesFor: myCounter
// => #(...)

// Events for a specific actor + method
Tracing tracesFor: myCounter selector: #increment
// => #(...)

Analysis Methods

Analysis methods compute rankings from aggregate stats. Each takes a limit parameter for the number of results.

// Top N methods by average duration (slowest first)
Tracing slowMethods: 10
// => #(...)

// Top N methods by call count (most called first)
Tracing hotMethods: 10
// => #(...)

// Top N methods by error + timeout rate
Tracing errorMethods: 5
// => #(...)

// Top N actors by message queue length (live snapshot over every
// registered actor, whether or not tracing is enabled)
Tracing bottlenecks: 5
// => #(...)

Live Health

Health methods provide point-in-time snapshots of actor and VM state.

// Per-actor health: queue depth, memory, reductions, status
Tracing healthFor: myCounter
// => #{queue_len => 0, memory => 1234, status => #waiting, ...}

// VM overview: schedulers, memory, process count, run queues
Tracing systemHealth
// => #{scheduler_count => 8, process_count => 42, ...}

Configuration

The trace event ring buffer has a configurable capacity (default 10,000 events). When full, the oldest events are evicted.

// Query current buffer capacity
Tracing maxEvents
// => 10000

// Set buffer capacity
Tracing maxEvents: 50000
// => nil

Typical Workflow

// 1. Create and exercise an actor
c := Counter spawn
10 timesRepeat: [c increment]

// 2. Check always-on aggregates (no enable needed)
(Tracing stats at: "class:Counter") at: "methods"
// => #{"increment" => #{calls => 10, ...}, ...}

// 3. Enable trace capture for detailed events
Tracing enable

// 4. Exercise the actor some more
5 timesRepeat: [c increment]

// 5. Query detailed traces
Tracing tracesFor: c selector: #increment
// => #(#{selector => #increment, duration_us => 38, ...}, ...)

// 6. Find bottlenecks
Tracing slowMethods: 5
// => #(...)

// 7. Clean up
Tracing disable
Tracing clear

Propagated Context (Advanced)

Actor messages automatically carry a propagated context map across boundaries. This is invisible to Beamtalk code — no user action is required. The context enables distributed tracing when OpenTelemetry is added as a project dependency: parent/child span correlation across actor calls works immediately with no Beamtalk changes. See ADR 0069 for details.

Relationship to Logging (ADR 0064)

Tracing and Logger address complementary observability concerns:

ConcernAPIADR
What is happening — log messages, debug outputLogger info:, Logger enableDebug:ADR 0064
How fast is it happening — timing, call counts, bottlenecksTracing stats, Tracing slowMethods:ADR 0069

Runtime logging configuration lives on class-side Logger (BT-3653, ADR 0129): Logger logLevel:, Logger logFormat:, Logger enableDebug: / disableDebug:, Logger debugTargets, Logger activeDebugTargets, Logger disableAllDebug and Logger loggerInfo. These moved from Beamtalk with no shim.


Application Telemetry Events (ADR 0069 amendment)

Telemetry lets Beamtalk code emit, and attach to, ordinary events on the BEAM telemetry bus, the library Phoenix, Ecto and Thousand Island use. Erlang and Elixir handlers, LiveDashboard, StatsD exporters and opentelemetry_telemetry see a Beamtalk event exactly as they would one emitted from Erlang. Like Tracing, it is a sealed class-side facade with no instances. Tracing observes actor dispatch; Telemetry is the event bus for your own application events. See the ADR 0069 amendment.

// Emit one event
Telemetry execute: #(#myapp, #cache, #miss)
  measurements: #{#count => 1}
  metadata: #{#key => "user:1"}
// => nil

// Time a block: emits [myapp, query, start] and [myapp, query, stop]
Telemetry span: #(#myapp, #query) metadata: #{#table => #users} do: [3 + 4]
// => 7

Attaching handlers

seen := Ets new: #seen type: #set
(Telemetry attach: #auditMisses to: #(#myapp, #cache, #miss) do: [:event :measurements :metadata |
  seen at: #last put: metadata]) unwrap
Telemetry execute: #(#myapp, #cache, #miss) measurements: #{#count => 1} metadata: #{#key => "k"}
(seen at: #last) at: #key
// => "k"
Telemetry detach: #auditMisses
// => nil

Skipping work nobody listens to

Telemetry hasHandlers: eventPrefix answers whether any handler (Beamtalk, Erlang or Elixir) is attached to an event whose name starts with eventPrefix, like Elixir libraries' :telemetry.list_handlers/1 check. An emitter can use it to skip a span's timestamps and metadata when nobody listens. eventPrefix is a non-empty List of Symbols, as for span:.

Telemetry hasHandlers: #(#myapp, #nobodyListens)
// => false

Telemetry is native: beamtalk_telemetry: each method is a self delegate pass-through to the runtime module (native: for stateless Objects), so a wrapped error names Telemetry and the selector. An emit costs about 0.2–0.4 µs more than a raw telemetry:execute/3 (docs/development/benchmarks.md).


Announcements — Typed Events (ADR 0093)

Announcements are Beamtalk's typed publish/subscribe substrate — a first-class Observer pattern. One part of a program (or the runtime itself) says "X happened" by announcing a typed event; other parts react by subscribing to that event's class. It is Pharo's Announcements + SystemAnnouncer, adapted to the BEAM: subscriptions are process-rooted and cleaned up by monitor, dispatch runs caller-side off concurrent ETS reads (no central bottleneck), and crashing handlers are isolated. See ADR 0093 for the full design.

The substrate lives in the core image (stdlib + runtime), not an optional package, because the system publishes through it — so it is always available, no dependency to add.

Events — subclass Announcement

An announcement is an immutable, typed payload describing a fact. Subclass Announcement and add field: slots for the event's data. Because Announcement is a Value, you get keyword-constructor ergonomics and field: accessors for free:

Announcement subclass: PriceChanged
  field: newPrice :: Number = nil

event := PriceChanged newPrice: 42
event newPrice    // => 42
event class       // => PriceChanged

Announcer — a per-instance dispatcher

Announcer new mints a fresh dispatcher handle (an opaque identity handle, like Pid). Subscribe with when:do:, publish with announce::

a := Announcer new

// Subscribe: returns a Subscription token. The handler block receives the event.
sub := a when: PriceChanged do: [:e | Transcript showCr: "now " ++ e newPrice printString]
sub class       // => Subscription
sub isActive    // => true

// Publish asynchronously (fire-and-forget). Every matching subscriber runs.
a announce: (PriceChanged newPrice: 42)    // prints "now 42"

// Stop listening.
sub unsubscribe
sub isActive    // => false

Subscription protocol

MessageMeaning
when: aClass do: aBlockEvaluate aBlock with the event on each announcement of aClass (or a subclass).
when: aClass send: sel to: receiverSend sel to receiver with the event as the sole argument.
when: aClass doOnce: aBlockDeliver exactly once, then auto-unsubscribe. Consumed atomically under concurrent announcers.
announce: anEventPublish asynchronously — returns immediately, handlers run fire-and-forget.
announceAndWait: anEventPublish synchronously — block until every handler completes (default 5 s timeout).
announceAndWait: anEvent timeout: msSynchronous publish with a custom per-handler timeout (Integer milliseconds or a Duration).
unsubscribe: receiverRemove every subscription receiver holds on this announcer.

Each when:… returns a distinct Subscription — a process may hold several to the same class, and re-subscribing never silently replaces an earlier one.

Synchronous vs asynchronous

announce: is asynchronous: it returns immediately and each handler runs in its own transient process, so a slow or crashing handler never blocks the publisher or its siblings. announceAndWait: is synchronous — it waits for every handler, with per-handler fault isolation and a timeout, so a wedged handler can never hang the caller:

a announceAndWait: (PriceChanged newPrice: 99)
// returns only after all handlers have run (or timed out)

A crashing handler is logged and isolated — other subscribers still run, and the announcer is unaffected:

a when: PriceChanged do: [:e | e boom]   // this handler will crash
a announce: (PriceChanged newPrice: 1)
// other subscribers still run; the crash is logged, not propagated

MRO matching — subscribe to a superclass

Dispatch walks the event's superclass chain at announce time, so subscribing to a superclass receives every subclass event. Delivery is de-duplicated per subscription:

Announcement subclass: UIEvent
UIEvent subclass: ButtonClicked
  field: buttonId :: String = ""

a when: UIEvent do: [:e | Transcript showCr: "ui event"]
a announce: (ButtonClicked buttonId: "submit")   // matches — "ui event"

SystemAnnouncer — watch the runtime live

SystemAnnouncer current is the singleton bus the runtime itself publishes onto. System facilities announce well-known discrete events; a tool subscribes once and filters by event class instead of wiring bespoke notification channels:

SystemAnnouncer current when: ActorSpawned do: [:e |
  Transcript showCr: e actorClass asString
]
Counter spawn    // the subscription fires: prints "Counter"

The system event classes (all Announcement subclasses):

EventFieldsAnnounced when
ActorSpawnedactorClass, pida Beamtalk actor starts
ActorStoppedactorClass, pid, reasonan actor stops
ClassLoadedclassNamea class is loaded into the image
ClassRemovedclassNamea class is removed
BindingChangedname, value, sessionIda workspace variable is assigned
FlushCompletedfilesWorkspace flush finishes writing source files
ObjectStateChangedpid, actorClass, changedSlotsa watched actor commits a state write (opt-in via beamtalk_object_watch)
SupervisionChildAdded(see ADR 0092)a supervised child is added
SupervisionChildCrashed(see ADR 0092)a supervised child crashes
NodeUpnodea visible node connects (ADR 0126 §8; hidden nodes never announce)
NodeDownnode, reasona visible node's connection is lost (reason is OTP's nodedown_reason, or #unknown)

SystemAnnouncer is async-only: announceAndWait: raises UnsupportedOperation, because the shared system bus can have many subscribers and a synchronous gather would be an unbounded process storm under rapid system events. Use announce: for the system bus, or a per-instance Announcer when you need synchronous dispatch.

[SystemAnnouncer current announceAndWait: anEvent] on: Error do: [:e | e kind]
// => unsupported_operation

Introspection — the third navigation sibling

The bus is navigable, alongside SystemNavigation (static classes) and ProcessNavigation (the live supervision tree). There are two levels.

Object-knows-itself — a live Announcer inspects its own subscriptions:

a subscriptions          // => a List of SubscriptionNode snapshots
a subscribersOf: PriceChanged   // => subscriptions to exactly PriceChanged
a subscriptionCount      // => total live subscriptions on the bus

Navigator-discovers-system — AnnouncementNavigation queries the graph:

AnnouncementNavigation default subscribersOf: ActorSpawned
AnnouncementNavigation default announcedClasses    // => distinct event types in use
AnnouncementNavigation of: anAnnouncer             // scope to one announcer

Each query returns a read-only snapshot of immutable SubscriptionNode value records (announcementClass, announcer, subscriber, handlerKind, once). To act on a subscription you cross back to the live Subscription token or the Announcer — the read-vs-mutate rule shared by all three navigators:

node := (a subscribersOf: PriceChanged) first
node announcementClass   // => PriceChanged
node subscriber          // => a Pid
node handlerKind         // => #do      (one of #do | #send | #doOnce)
node once                // => false

Announcements vs telemetry (ADR 0069)

Beamtalk has two event buses; reach for the right one. Measure with telemetry (spans, counters, durations — Actor Observability and Tracing); react with Announcements (typed domain events you subscribe to in app logic):

telemetry (ADR 0069)Announcements (ADR 0093)
PurposeMeasurement — spans, countersTyped domain events you react to
Event identitystring list [beamtalk, actor, dispatch]Announcement subclass (typed, MRO)
Deliverysync, fire-and-forgetasync or sync; isolated; monitored
Livenessnone (module-fun handlers)monitor-based per subscriber

Liveness note. A subscription is bound to the subscribing process and auto-removed when that process dies — no manual cleanup leaks. In the REPL each turn evaluates in a fresh worker process, so a subscription made at one prompt is gone by the next; subscribe, announce, and observe within a single expression (or from a long-lived actor) when you need a subscription to persist.

Per-instance isolation. Each Announcer new mints an independent dispatcher — subscriptions on announcer A are never matched by an announce: on announcer B, even for the same event class. SystemAnnouncer is the canonical multi-subscriber bus for system-wide events. Cross-node delivery to a connected node works. The optional beamtalk-announcements package adds RecordingAnnouncer (a test double that records instead of dispatching) and AnnouncementTelemetry (re-emits announcements as telemetry events). Partition tolerance and replay are planned for that package (BT-4600).


Distribution — Location-Transparent Actors (ADR 0126)

Beamtalk actors are location-transparent: the same . (sync) and ! (cast) sends that work between local actors work identically against an actor running on another BEAM node in the cluster. (Future-returning async sends do not cross nodes: they raise unsupported_operation at once, ADR 0126 amendment BT-4989.) There is no special "remote actor" type — an Actor reference is an Actor reference, whether the process behind it lives here or across the network.

A runnable three-node example, with a CI end-to-end run, is examples/cluster: a coordinator farms jobs out to two worker nodes, loses one mid-call, and reassigns the work.

Distribution builds directly on the supervision, announcement, and value-object machinery described earlier in this document; see ADR 0126 for the full design, including the failure-mode analysis and security model this section summarizes.

Node — a first-class value

Node wraps a BEAM node identity (name@host). It is a value, not a proxy: two Nodes are equal iff their names are equal, and constructing one never touches the network.

Node current                                    // => Node(nonode@nohost)
worker := (Node named: #'worker@localhost') unwrap
worker name                                     // => #'worker@localhost'
Node connected                                  // => #()  (visible connected nodes)
worker connect                                  // => Result ok: Node(worker@localhost)
worker isConnected                              // => true
worker disconnect                               // => true

disconnect does not keep the node away. The next send to an actor on that node (or connect/ping) reconnects it automatically (ADR 0126 §9, item 4; not when the node runs with -kernel dist_auto_connect never), and NodeUp fires again. Use it to drop a connection, not to fence a node off.

connect (and ping, which auto-connects) apply a security policy (see Security, below): a same-host connection always succeeds; an off-host connection is refused with kind = insecure_distribution unless this node runs TLS distribution. Deciding whether a host is this host takes a name lookup, which is bounded at 2 seconds per address family: a host that has not resolved by then is treated as off-host. Node named: only validates the name@host shape and never touches the network, so it always succeeds for a well-formed name — reachability is only proven by connect/ping.

Remote spawn and lookup

Every actor spawn/lookup class-side selector gains an on: variant that targets a specific Node. Syntax, return types, and error kinds mirror the local form exactly — remote spawn always answers a Result, because reaching another node is an expected failure (ADR 0060), not a programming error:

worker := (Node named: #'worker@localhost') unwrap
c := (Counter spawnOn: worker) unwrap
c node                                          // => Node(worker@localhost)
c isRemote                                      // => true
c increment                                     // an ordinary sync send — works identically to a local actor
SelectorLocal formRemote form
Anonymous spawnspawnspawnOn: node
Named spawn (state args)spawnWith: argsspawnWith: args on: node
Named + registered spawnspawnAs: namespawnAs: name on: node
Lookup by registered namenamed: namenamed: name on: node
List every registered actorallRegisteredallRegisteredOn: node

Remote spawn is not idempotent. A timeout after the far-side spawn actually succeeded leaves an unowned actor running on the target node — the spawning session has no way to tell "it never happened" from "it happened, but the reply was lost". A named spawn (spawnAs:on:) retried after name_registered can be recovered with named:on:; an anonymous spawnOn: has no such recovery — retry only when idempotency doesn't matter, or use a named spawn.

Remote spawn creates no link and no local tracking. The spawned actor is never linked back to the spawning process (a link across a node boundary would turn every partition into a local crash), and the spawning workspace does not track it — ActorSpawned fires on the target node, not the caller's. The actor outlives the spawning session until something else stops it.

Cluster-unique names — scope: #global

A node-local registered name (spawnAs:, ADR 0079) is only visible on the node that registered it. Requesting scope: #global instead registers the name cluster-wide, backed by OTP's global module:

leader := (Scheduler spawnAs: #scheduler scope: #global) unwrap
// from any node in the cluster:
s := (Scheduler named: #scheduler scope: #global) unwrap
s tick

scope: #global is opt-in — the default stays node-local — and comes with real operational cost, not just a lookup convenience:

Mesh side effects. global keeps a fully connected mesh between every node that uses it, and OTP 25+ enables prevent_overlapping_partitions by default: on partial connectivity, global actively disconnects nodes to restore a consistent view. A program using scope: #global will observe NodeDown events caused by global itself, not by an actual network failure — don't assume every NodeDown means a real partition. global also inherits the full-mesh registry's known scaling limits (every node locks the global name table during a registration) — reach for it deliberately, not as the default choice for cluster-wide lookup.

Connect waits for global. Node connect answers only after OTP's global has synced names with the new peer, so a scope: #global name registered right after connect is visible from the peer at once.

Registration is bounded. Registering a global name waits for global's cluster-wide lock, which another node may be holding. spawnAs:scope: #global waits at most 5 seconds for it; if the lock is not free by then the new actor is stopped and the result is an Error tagged timeout, whose details name the requested name. A supervised withName:scope: #global child in that situation is not started (a warning is logged), like one whose name is held on another node.

When a netsplit heals and the same global name was registered on both sides, Beamtalk's own resolver keeps the older registrant (by start time) and stops the other with a #globalNameConflict reason — never OTP's default exit(Pid, kill), so the losing actor's terminate still runs and its ActorStopped announcement carries the reason. A supervised scope: #global child that loses stays down rather than restart-looping: its start is ignored while the name is held on another node (with a logged warning). Under one_for_one its siblings are unaffected. Nothing watches the name: the child stays down until a later restartChild: finds it free (Result ok: nil while the name is still held).

The wire — what crosses a node boundary, and what doesn't

A send to a remote actor is encoded before it leaves the sender and decoded on arrival — transparently, with no change to the sending code. Every argument and result is walked and classified:

What you sendCrosses the wire as
Numbers, Strings, Symbols, Value subclasses, NodeCopied, Value instances enveloped (version-tagged, ADR 0123/0125)
Actors, PidAllowed — pids are node-qualified natively; a registered-name reference is rewritten to carry its origin node
A class object (e.g. Counter)Rewritten to a by-name reference, resolved against the receiving node's own class registry — a class object never crosses as a remote process reference. One that skips the wire (an FFI or rpc/erpc result, a raw Erlang message) is resolved the same way: at the FFI boundary (the result itself, or an {ok, _} payload), or, nested deeper, when it is sent a message (BT-5274); until then a nested one is not == to this node's class. A class not registered on the receiving node raises class_not_found
Blocks (closures)Allowed, like Erlang funs — see the caveat below
Port, FileHandle (HandleScoped(#process))Rejected at encode time: kind = not_serialisable
Ets, AtomicCounter, Timer, Subscription (HandleScoped(#node))Rejected at encode time: kind = not_serialisable — a handle that names a resource on this node is meaningless on another
An unassigned late slotTravels as absent; the receiver's first read raises UninitializedStateError

A block whose defining class isn't loaded (at the same version) on the node where it runs raises kind = remote_code_mismatch there — for a block invoked during the call that received it, that's the callee, relayed back to the sender like any other callee error; for a block stored and invoked later, it surfaces wherever it's eventually invoked.

Version skew is handled per message, not per connection. An older envelope is migrated forward through the receiving class's migrateFromVN: chain; a newer envelope than the receiver knows is refused before any migration runs, with kind = shape_version_ahead. Two directions of that refusal have distinct consequences:

The timeout-vs-node_down caveat. The ordinary 5000 ms sync-send timeout (ADR 0043) applies unchanged across the network. Erlang only detects a silent partition after net_ticktime (default 60 s) — so during a real partition, a sync send will normally raise timeout before anything raises node_down. These mean different things: timeout says "no answer arrived in time" (the call may still be running, or may already have completed on the far side — a timed-out call is at-most-once-reply, not at-most-once-execution, identical to a local gen_server:call timeout); node_down says "the runtime has confirmed the node is gone". Don't treat a timeout as proof the remote actor never ran.

Lifecycle selectors on a remote actor (BT-5192). isAlive, kill and stop follow the same rule: when the actor's node cannot be reached they raise node_down (or timeout when it does not answer in time), never an answer that guesses. isAlive asks the actor's node (up to 5 seconds) and answers true or false from there (an actor found with named:on: whose node cannot be reached raises node_down too, rather than answering false); kill raises node_down when the kill signal is lost; stop raises node_down instead of actor_dead. Across a partition the actor may well still be running.

Cluster events

Node membership and shape-version skew are observed through the ordinary Announcements substrate, not a polling API — subscribe to the event class you care about:

SystemAnnouncer current when: NodeUp do: [:e |
  Transcript showCr: "joined: ", e node name asString
]
SystemAnnouncer current when: NodeDown do: [:e |
  Transcript showCr: "lost ", e node name asString, " (", e reason asString, ")"
]
SystemAnnouncer current when: NodeShapeSkew do: [:e |
  Transcript showCr: e node name asString, ": ", e className asString,
    " local v", e localVersion printString, " remote v", e remoteVersion printString
]
SystemAnnouncer current when: NodeVersionSkew do: [:e |
  Transcript showCr: e node name asString, " runs Beamtalk ",
    e remoteBeamtalkVersion printString, " wire v", e remoteWireVersion printString
]

Supervision-tree introspection reaches across nodes too: ProcessNavigation on: aNode snapshots the target node's default-scope supervision tree via erpc (the same walk ProcessNavigation default runs locally, executed remotely) and returns Result(ProcessNavigation, Error) — every SupervisionNode in the result carries a node field naming which node it came from:

(ProcessNavigation on: worker) unwrap tree nodesOfKind: #beamtalkActor

aNode shapeSkew answers a node's current shape-skew count (how many classes differ in version from this node's own); mapping it over Node connected gives the cross-surface nodes operation reached identically from the REPL, MCP, and LiveView surfaces (see docs/development/surface-parity.md). The per-node queries aNode actors, actorsOf:, actorAt:, processes and supervisors reach a peer via erpc and answer Result values; a down peer yields an Error tagged node_down, never a raise.

Security model

connect (and anything that connects as a side effect: ping, a remote spawn, shapeManifest) applies a host policy: a same-host connection is always allowed; an off-host connection is refused with kind = insecure_distribution unless this node runs TLS distribution (-proto_dist inet_tls). This guard is advisory for the language surface, not an enforcement boundary — raw net_kernel calls via Erlang FFI, and Erlang's own auto-connect on a send to a remote pid, bypass it. There is no cookie API at the language level (the cookie is a VM-level -setcookie concern, ADR 0020/0058).

Only visible nodes participate in distribution transparency (spawn, lookup, cluster events); a hidden node (-hidden) never appears in Node connected, never fires NodeUp/NodeDown, and is excluded from shape-skew checks — hidden nodes are for tooling that observes or attaches to a cluster without joining it as a peer. Beamtalk's own attach front (ADR 0097) starts as a hidden node (BT-3616), so attaching to a cluster never fires NodeUp on its members.


Not Yet Supported

Forms the documentation or an ADR describes that the compiler does not accept or honour yet, in one place. The Today column says whether each one is rejected with a diagnostic or quietly ignored.

FormTodayReference
Trait aliasing: clause (uses: T aliasing: #{#new => #old})Reserved. The parser consumes it for recovery and rejects it.ADR 0127
Parametric aliases (type Option(T) = T | Nil) and recursive aliases (type Json = ... | List(Json))Rejected with a diagnostic; they need lazy alias resolution.Named Type Aliases
Rest patterns in match: arms (#[a, ...rest] -> ...)Supported in destructuring assignment only; in a match: arm the compiler reports "not yet supported".Rest Patterns in Destructuring
Package-bundled FFI type stubsOnly the project-local stubs/ directory is searched; stubs shipped in a dependency are ignored, with no diagnostic.FFI Type Stub Files

Namespace and Class Visibility

Within a package (and the REPL workspace), Beamtalk uses a flat namespace — all classes are visible to each other, with no import or export declarations. Across packages, dependencies are declared in beamtalk.toml and a dependency's classes are referenced by their short name, with qualified package@Class names available to resolve collisions (ADR 0070). The original v0.1 flat-global-namespace decision is ADR 0031 (superseded by ADR 0070).

How loading works

When you load a file with Workspace load: "path/to/file.bt":

  1. The file is compiled to a BEAM module named bt@class_name (ADR 0016)
  2. The module's on_load hook registers each class with the class registry
  3. If a class with the same name already exists (from a previous load), the new definition hot-reloads the class — existing actors continue to run with the new code on their next message
  4. The class records its source file path for future reload calls
// Works from compiled code too
(Workspace load: "examples/counter.bt")
// => #(Counter)

c := Counter spawn
c increment
// => 1

// Reload by class name (class-based, not file-based)
Counter reload
// => Counter

Class collision warnings

If two files from different packages define the same class name, the BEAM module atoms differ (e.g. bt@counter vs bt@other_pkg@counter), and Beamtalk emits a warning to alert you to the collision:

Workspace load: "my_app/counter.bt"
// => #(Counter)

Workspace load: "other_pkg/counter.bt"
// => #(Counter)
// warning: Class 'Counter' redefined (was bt@counter, now bt@other_pkg@counter)

The second definition wins — the class is hot-reloaded with the new implementation.

Naming conventions

To avoid collisions, use package-specific prefixes for classes that might conflict:

// ❌ Too generic — likely to collide with other packages
Object subclass: Logger ...

// ✓ Package-scoped name — unlikely to collide
Object subclass: MyAppLogger ...

Protected stdlib class names

Beamtalk's standard library classes (e.g., Integer, String, Array, Actor, Object, Boolean) are protected against redefinition in user code. There are two layers of protection:

Compile-time warning — fires for all stdlib class names (both stdlib/src/*.bt classes and runtime-only built-ins like Future):

// ❌ Compile-time warning: Class name `Integer` conflicts with a stdlib class.
//    Loading will fail because stdlib class names are protected.
Value subclass: Integer
  field: x = 0

Runtime load-time error — fires for fully-featured stdlib classes that are backed by stdlib/src/*.bt source files and loaded under the bt@stdlib@* module prefix. Attempting to load user code that redefines one of these returns a structured error:

Workspace load: "my_integers.bt"
// => Error: Cannot redefine stdlib class 'Integer'
//    Hint: Choose a different name. `Integer` is a protected stdlib class name.

If you need to customise stdlib behaviour, subclass instead of redefining:

// ✓ Subclass is fine
Integer subclass: SafeInteger
  divSafe: divisor =>
    divisor == 0 ifTrue: [^0]
    self / divisor

Namespace

Within a package, class names must be unique. Across packages, the namespace and dependency system (ADR 0070) makes each declared dependency's classes available by their short name; collisions between dependencies are a compile error, resolved with qualified package@Class names. See the Package Management guide for beamtalk.toml, dependencies, and qualified names. ADR 0031 (superseded by ADR 0070) records the original v0.1 flat-namespace decision.

Package-Qualified Superclass

A class definition may name its superclass as package@Class, which picks the class from that package even when two dependencies define a class with the same short name:

stdlib@Value subclass: Celsius
  degrees => 21

json@Parser subclass: LenientParser is the same form with a dependency named json. The qualified name is the same class as the short name (stdlib@Integer == Integer), so the subclass inherits exactly as it would from the short name. In a package (a directory with a beamtalk.toml), a qualifier that is neither the current package, stdlib nor a declared dependency is a compile error (Unknown package 'json' in superclass reference 'json@Parser'). A single file compiled with no manifest has no package set to check against, so the qualifier is not validated there.

Visibility and Access Control (ADR 0071)

Beamtalk classes and methods are public by default — visible to any package. The internal modifier restricts visibility to the defining package only. Enforcement is compile-time only, with zero runtime overhead.

Core principle: Visibility controls dependency, not knowledge. Internal classes and methods are fully visible to browsing, reflection, and documentation tools — you just cannot name them in compiled code from outside the package. The REPL's :browse, :doc, and :source commands work on internal items normally.

Class-Level internal

Mark a class as internal to hide it from other packages:

// Public (default) — available to any package
Actor subclass: HttpClient
  get: url => ...

// Internal — only visible within this package
internal Actor subclass: ConnectionPool
  state: connections = #{}

  acquire => ...
  release: conn => ...

Cross-package references to internal classes produce a compile error (E0401):

Class 'ConnectionPool' is internal to package 'http' and cannot be referenced from 'my_app'
  help: 'ConnectionPool' is declared 'internal' in package 'http'

Method-Level internal

Mark individual methods as internal to hide implementation helpers on public classes:

Actor subclass: HttpClient
  state: config = #{}

  // Public — part of the package API
  get: url => ...
  post: url body: body => ...

  // Internal — implementation details, not callable from outside the package
  internal buildHeaders: request => ...
  internal retryWithBackoff: block maxAttempts: n => ...

When the compiler can determine the receiver type (via type annotations, literal class references, or type inference), cross-package sends to internal methods produce a compile error (E0403):

Method 'buildHeaders:' is internal to package 'http' and cannot be called from 'my_app'
  help: 'buildHeaders:' is declared 'internal' in 'HttpClient'

For untyped dynamic sends where the receiver type is unknown, no enforcement — the message send succeeds at runtime, consistent with the "visibility controls dependency, not knowledge" principle.

Combining Modifiers

internal composes with all existing class modifiers in any order:

// Internal abstract base — must be subclassed within the package
internal abstract Actor subclass: InternalAbstractBase
  state: label = "base"
  getLabel => self.label
  compute => self subclassResponsibility

// Internal sealed — cannot be subclassed, even within the package
internal sealed Actor subclass: InternalSealedCache
  state: data = 0
  store: val => self.data := val
  retrieve => self.data

// Internal typed — type annotations required on methods
internal typed Actor subclass: InternalTypedConfig
  state: setting :: Integer = 0
  getSetting -> Integer => self.setting
  setSetting: val :: Integer -> Integer => self.setting := val

// Modifier order is flexible
abstract internal Actor subclass: AlsoValid
  ...
CombinationValid?Notes
internal sealedYesPrevents subclassing even within the package
internal abstractYesInternal base class, must be subclassed within the package
internal typedYesInternal class with type annotation requirements
Stacking orderAnyinternal can appear anywhere in the modifier list

Library Author Patterns

A typical package exposes a few public classes and hides implementation details:

// json/src/parser.bt — Public API
Object subclass: Parser
  /// Parse a JSON string into a Beamtalk value.
  parse: input :: String => ...

// json/src/parser_state.bt — Internal implementation
internal Value subclass: ParserState
  field: position = 0
  field: buffer = ""

// json/src/token_buffer.bt — Internal implementation
internal Value subclass: TokenBuffer
  field: tokens = #()

Leaked visibility — if an internal class appears in the public signature of a public method, the compiler emits a hard error (E0402). This prevents accidentally exposing implementation types:

Internal class 'TokenBuffer' appears in public signature of 'Parser >> tokenize:'
  help: 'TokenBuffer' is declared 'internal' — make it public, or change the type

All methods on an internal class are effectively internal. The method-level modifier is only meaningful on public classes. The check applies equally to a same-file >> method (Parser >> tokenize: …) and to a live >> patch.

Metadata

Visibility is recorded in __beamtalk_meta/0 as a compile-time constant atom (public or internal). Tooling (LSP, REPL completions) uses this field to filter internal items from cross-package suggestions while still showing them in :browse and :doc output.

__beamtalk_meta/0 also carries toolchain provenance keys (beamtalk_version and otp_release as binary strings) when the module was compiled by a known toolchain (ADR 0098). Workspace attach and tooling use these to detect stale modules without re-reading the on-disk build stamp.

See ADR 0071 for the full design, including edge cases (subclassing, protocol conformance, extension methods, perform: dynamic sends) and the enforcement model.


Smalltalk + BEAM Mapping

Smalltalk/Newspeak ConceptBeamtalk/BEAM Mapping
Value objectValue subclass: with field: — plain Erlang map (no process)
ActorActor subclass: with state: — BEAM process (gen_server)
Module/utility classObject subclass: — no Beamtalk-managed data; class methods or runtime-backed instances
ClassModule + constructor function
Instance variable (immutable)field: — value map field
Instance variable (mutable)state: — gen_server state map field
Field access (self.x)maps:get('x', State)
Field write (self.x := v)maps:put('x', v, State) (Actor only; compile error on Value)
. message sendgen_server:call — sync, blocks for result
! message sendgen_server:cast — async fire-and-forget
BlockErlang fun (closure)
ImageRunning node(s)
WorkspaceConnected REPL to live node (Workspace class-side facade)
Class browserREPL introspection: Beamtalk allClasses, Beamtalk help: Class

Standard Library

109 classes implemented and tested (stdlib/src/*.bt; see Stdlib Implementation Status for the current per-class method audit). For detailed API documentation, see API Reference.

Core types:

ClassDescription
Integer, Float, NumberArbitrary precision arithmetic
String, Symbol, CharacterUTF-8 text (String is a subclass of Binary), interned symbols, Unicode characters
Boolean, True, FalseBoolean values with control flow
Nil (UndefinedObject)Null object pattern
BlockFirst-class closures

Collections:

ClassDescription
BinaryByte-level data — Collection subclass, parent of String (ADR 0086)
ArrayFixed-size indexed collection — O(log n) at:/at:put:, canonical value equality regardless of edit history (ADR 0090)
ListLinked list with fast prepend (#() syntax)
DictionaryKey-value map
SetUnordered unique elements
BagMultiset — allows duplicate elements, counts occurrences
TupleFixed-size heterogeneous container
QueueO(1) amortised FIFO queue
IntervalArithmetic sequence (1 to: 10, 1 to: 10 by: 2)
StreamLazy, closure-based sequences (ADR 0021)
EtsShared in-memory tables (BEAM ETS wrapper)

Actors and concurrency:

ClassDescription
ActorBase class for all actors (BEAM processes)
ServerAbstract Actor subclass for BEAM-level OTP interop (handleInfo:) (ADR 0065)
Supervisor, DynamicSupervisorOTP supervision trees (ADR 0059)
AtomicCounterLock-free shared counter
TimerPeriodic and one-shot timers (linked to calling process via spawn_link)
ParallelBlock-based fan-out/join combinators (all:, all:timeout:, any:) — spawns one linked+monitored process per block, blocks the caller, returns plain Result values; no awaitable future/promise value is ever exposed (BT-2974)
Pid, Reference, PortBEAM primitive types

Error handling:

ClassDescription
ResultTyped success/error for expected failures (ADR 0060)
Error, RuntimeError, TypeErrorError hierarchy
BEAMError, ExitError, ThrowErrorBEAM exception wrappers
ExceptionBase exception type

I/O and system:

ClassDescription
File, FileHandleFile system operations
Subprocess, ReactiveSubprocessOS process execution (ADR 0051)
OS, SystemPlatform info and system operations
JsonData serialisation (JSON)
JsonMapping, JsonMappableDeclarative JSON field mapping (BT-2819) — see § JsonMapping
RegexRegular expression matching
DateTime, Time, DurationDate/time operations (DateTime>>weekday → ISO Monday=1..Sunday=7)
RandomRandom number generation
DigestCryptographic hash functions and HMAC

Networking (in beamtalk-http):

ClassDescription
HTTPServer, HTTPClientHTTP server and client
HTTPRouter, HTTPRoute, HTTPRouteBuilderDeclarative HTTP routing
HTTPRequest, HTTPResponseRequest/response objects

Data formats (in beamtalk-yaml):

ClassDescription
YamlYAML parsing and serialisation — not part of stdlib; add it as a package dependency (Package Management guide)

Observability:

ClassDescription
TracingActor observability and performance telemetry — always-on aggregates + opt-in trace capture (ADR 0069)

Reflection and meta:

ClassDescription
Class, Metaclass, ClassBuilderClass reflection and dynamic class creation
BehaviourShared behaviour protocol
CompiledMethodMethod introspection
StackFrameStack trace inspection
TestCase, TestResult, TestRunnerBUnit test framework — TestCase is a Value subclass with functional setUp (ADR 0014)

Binary — Byte-Level Data

Binary is a sealed Collection subclass for byte-level data. String is a subclass of Binary that adds grapheme-aware text operations. The class hierarchy is Collection > Binary > String (ADR 0086).

On BEAM, a Binary is a bare Erlang binary(), while a String is the tagged tuple {beamtalk_string, Bin} holding UTF-8 bytes (BT-4173). Representation is by construction: Binary fromBytes: answers a Binary even when the bytes happen to be valid UTF-8, and a String literal answers a String. The runtime never sniffs bytes to decide — class answers the construction type, and dispatch follows the class.

A String never equals a Binary, even with the same bytes. "abc" == (Binary fromBytes: #(97, 98, 99)) is false (in either order, and for =:=), their hashes differ, a Dictionary keyed by "abc" does not find the Binary, and a Set holds both. Convert first: aBinary asString (validated, answers a Result) or asStringUnchecked. Because the mismatch fails quietly — bytes from Erlang looked up in a String-keyed Dictionary just come back absent — the compiler gives a binary-string-compare hint (BT-4257) when a value that is provably a raw Binary meets a String-typed value in ==, /=, =:= or =/=, as the key of a Dictionary(String, V) at:, at:ifAbsent:, at:put:, includesKey: or removeKey:, or as the argument of a Set(String) includes: or add::

hint[binary-string-compare]: a Binary never equals a String, even with the same bytes
  = help: convert the Binary first with `asString` (validated, answers a Result) or `asStringUnchecked`

"Provably a raw Binary" means built by a Binary-only producer — Binary fromBytes:/fromIolist:/withAll:/serialize:/empty, a Digest hash, <<...>>, or concat:/part:size: of one of those — or a local last assigned from one. A value merely typed Binary (a parameter, a field, a method result) may be a String (String is a subclass of Binary), so it never triggers the hint, and neither does Dynamic. For the same reason a Dictionary(Binary, V) probed with a String is not reported. Suppress the hint with @expect binary_string_compare, or package-wide with binary-string-compare = "off" under [diagnostics] in beamtalk.toml.

// Construction
bin := Binary fromBytes: #(104, 101, 108, 108, 111)
bin := Binary fromIolist: #("hello", " ", "world")
bin := Binary empty                  // canonical empty binary (<<>>)
bin := <<104, 101, 108, 108, 111>>   // bit syntax, see Binary construction (ADR 0143)

// Byte access (1-based, Collection protocol) — elements are byte Integers
bin := Binary fromBytes: #(104, 101, 108)
bin at: 1                    // => 104
bin size                     // => 3 (byte count)

// Byte access (0-based, Erlang-compatible)
bin byteAt: 0                // => 104 (byte value)

// Zero-copy slicing
bin := Binary fromBytes: #(1, 2, 3, 4, 5)
bin part: 1 size: 3          // => Binary (bytes 2, 3, 4)

// Concatenation
a := Binary fromBytes: #(1, 2)
b := Binary fromBytes: #(3, 4)
a concat: b                  // => Binary (1, 2, 3, 4)

// Byte list conversion
bin toBytes                   // => #(1, 2, 3, 4, 5)
Binary fromBytes: #(65, 66)  // => Binary

// UTF-8 decoding (Binary → String) answers a Result uniformly (BT-4169)
((Binary fromBytes: #(104, 101, 108, 108, 111)) asString) unwrap  // => "hello"
(Binary fromBytes: #(104, 101, 108, 108, 111)) asStringUnchecked   // => "hello"

// Invalid UTF-8: asString answers `Result error:` with the byte offset
((Binary fromBytes: #(255, 254)) asString) isError                // => true
((Binary fromBytes: #(255, 254)) asString) error message          // => "Invalid UTF-8 at byte offset 0"

// Serialization (class methods)
etf := Binary serialize: #(1, 2, 3)
Binary deserialize: etf               // => #(1, 2, 3)
Binary deserializeWithUsed: etf       // => #(value, bytesConsumed)

// Collection protocol — Binary is a collection of byte Integers
bin := Binary fromBytes: #(65, 66, 67, 68, 69)
bin collect: [:b | b]         // => Binary (65, 66, 67, 68, 69)
bin select: [:b | b /= 67]    // => Binary (65, 66, 68, 69)
bin includes: 66              // => true
bin isEmpty                   // => false

// Byte-level substring search (BT-4190)
data := Binary fromBytes: #(1, 2, 3, 4, 5, 3, 4)
needle := Binary fromBytes: #(3, 4)
data includesSubstring: needle   // => true
data indexOf: needle             // => 3 (1-based byte index of first match)
data indexOf: (Binary fromBytes: #(9, 9))  // => nil (not found)
(Binary fromBytes: #()) includesSubstring: (Binary fromBytes: #())  // => true
(Binary fromBytes: #()) indexOf: (Binary fromBytes: #())            // => nil

Method override table (Binary vs String):

MethodOn BinaryOn String
at: indexbyte Integer (1-based)grapheme String (1-based)
sizebyte countgrapheme count (alias for length)
byteAt: offsetbyte value (0-based)inherited — byte value (0-based)
do: blockiterate bytes, answers niliterate graphemes
collect: / select: / reject:byte-level, answer Binarygrapheme-level, answer String
includes: / detect: / anySatisfy: / allSatisfy:byte-level (Integer elements)grapheme-level (String elements)
part: offset size: nbyte-level slice, returns Binaryinherited — byte-level slice, returns Binary
concat:byte concatenation, returns Binaryinherited — byte concatenation, returns Binary
asStringResult ok: String, or Result error: with offsetno-op, returns self
asStringUncheckedunchecked cast to Stringno-op, returns self
includesSubstring:byte-level substring testgrapheme-level substring test
indexOf:1-based byte index or nil1-based grapheme index or nil

(byteSize was removed in BT-4173 — size is the byte count on Binary.)

Binary vs String at Runtime

A Binary and a String holding the same bytes are different values with different classes: "hi" is {beamtalk_string, <<"hi">>} (class String) while Binary fromBytes: #(104, 105) is <<"hi">> (class Binary), even though both render as "hi". class answers the construction type, and dynamic dispatch of size, at:, do:, and the Collection protocol follows the class — byte-level on Binary, grapheme-aware on String:

bytes := Binary fromBytes: #(255, 254, 253)
bytes class name    // => "Binary"
bytes size          // => 3 (bytes, not graphemes)
bytes printString   // => "<<FF FE FD>>" (hex — never raw invalid UTF-8)

text := Binary fromBytes: #(104, 105)
text class name     // => "Binary" (construction type — never sniffed)
text size           // => 2
text at: 1          // => 104 (byte Integer, not "h")

Equality is representation-strict: "a" =:= (Binary fromBytes: #(97)) is false, and so is == — a String never equals a Binary. Convert explicitly (asString / asStringUnchecked) before comparing across the two.

The byte/text distinction also holds at the boundaries: FFI calls and file reads answer Binary for bytes (Erlang file read_file:, File readBinary:), while text entry points (string literals, File readAll:, JSON string leaves) answer String. Native code validates untrusted bytes with UTF-8 checks before constructing a String; only asStringUnchecked skips validation, and only callers that already know the bytes are text may use it.

// Byte loop over Binary data — elements are Integers throughout
checksum: data =>
  (0 to: data size - 1) inject: 0 into: [:acc :i | acc + (data byteAt: i)]

Bitstring — Unaligned Bits

A Bitstring is a sequence of bits that is not a whole number of bytes (ADR 0141). The class follows the value's shape, as in Erlang: a BEAM bitstring whose bit size is a multiple of 8 is a binary (Binary, or String), and any other bitstring is a Bitstring. Bitstring is a sealed sibling of Binary, not its superclass or subclass, so isKindOf: Binary and :: Binary are false for it. Bitstrings come from binary patterns: a /bitstring (or /bits) segment binds whatever bits are left.

tail := (Binary fromBytes: #(234)) match: [<<_:3, rest/bitstring>> -> rest]
tail class                // => Bitstring
tail bitSize              // => 5
tail toBits               // => #(0, 1, 0, 1, 0)  (most significant bit first)
tail printString          // => "<<10:5>>"  (Erlang notation)
tail asBinary isError     // => true  (kind #unaligned_bitstring)
(Binary fromBytes: #(1, 2)) bitSize   // => 16
SelectorAnswer
bitSizenumber of bits (also on Binary: 8 × byte count)
toBitsList(Integer) of 0/1, most significant bit first
concat:the joined bits — a Binary when byte-aligned, else a Bitstring; a String argument joins by its bytes. Binary>>concat: stays bytes-only: a Bitstring argument is a type_error, so join bits from the Bitstring side
asBinaryalways Result error: of kind #unaligned_bitstring; no silent padding or truncation
printString / displayStringErlang notation, e.g. <<2:3>>
=:=, ==, hashstructural equality, inherited

The byte protocol of Binary and Collection is deliberately not understood: size, do:, at:, byteAt:, part:size:, toBytes, includesSubstring:, indexOf:, asString, asStringUnchecked, asBase64, asBase64Url, asHex, collect:, select:, inject:into:, isEmpty, includes:, and the rest. Each raises a structured does_not_understand whose hint names the bit size:

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

Accessing an Empty Collection

Element accessors and subsequence operations differ deliberately on an empty collection (BT-3021):

Element accessors raise empty_collection. first, last, and at: have no element to answer, and nil would be indistinguishable from a stored nil:

#() first                  // raises empty_collection
#() last                   // raises empty_collection
#() at: 1                  // raises empty_collection
"" first                   // raises empty_collection
"" at: 1                   // raises empty_collection
#[] first                  // raises empty_collection
#[] last                   // raises empty_collection
(Array withAll: #()) at: 1 // raises empty_collection
(Binary fromBytes: #()) at: 1   // raises empty_collection
(1 to: 0) first            // raises empty_collection
#() max                    // raises empty_collection (also min, average)

Queue predates this kind and keeps its own empty_queue for compatibility, but classifies as a RuntimeError like the rest of the family, so a single on: RuntimeError do: covers both.

empty_collection is a RuntimeError, so it can be caught on its own — crucially, separately from a genuine typo, which raises does_not_understand:

[orders first] on: RuntimeError do: [:e | e kind =:= #empty_collection]

Ordered vs. unordered: first/last vs. anyOne (BT-3027). Only collections with a defined iteration order — Array, List, Interval, String, Binary — have first/last. Set, Bag, and Dictionary are unordered and deliberately do not have first/last: either name would misleadingly promise an ordering guarantee the collection does not make. Sending first or last to one of them raises does_not_understand, exactly like any other unimplemented selector — it is not treated as an empty-collection condition:

Set new first                    // raises does_not_understand
(Bag withAll: #(1, 2)) last      // raises does_not_understand

Instead they answer anyOne — some element with no ordering guarantee (the answer may differ between calls), raising empty_collection when there is nothing to answer. anyOne is defined once on the abstract Collection class in terms of do:, so every collection has it, but it is most useful on the unordered three:

(Set new add: 1) anyOne           // => 1
Set new anyOne                    // raises empty_collection
(Bag withAll: #(1, 1, 2)) anyOne  // => 1 or 2 — no ordering guarantee
#{#a => 1} anyOne                 // => 1 (a *value*, consistent with do:)

If you specifically want the order asList currently answers in, convert first: aSet asList first. That order is an implementation detail (Set's asList happens to sort by term order today), not a contract — prefer anyOne when any single element will do.

Subsequence operations stay total and answer the empty collection. rest, take:, and drop: all have a well-defined answer on empty, so they never raise — which keeps recursive idioms working without a guard at every step:

#() rest                   // => #()
#() take: 3                // => #()
#() drop: 3                // => #()
#() sum                    // => 0 (identity element, unlike max/min)

An out-of-range index into a non-empty collection is a different condition again, and raises index_out_of_bounds:

#(1, 2, 3) at: 9           // raises index_out_of_bounds
#(1, 2, 3) at: 0           // raises index_out_of_bounds (index < 1 is malformed)

Interval>>at: always raises index_out_of_bounds, never empty_collection, for any out-of-range index — including on an empty interval. This differs from first/last (which do raise empty_collection on an empty interval): at: is a bounds-checked keyed accessor like Array>>at:, and empty_collection is reserved for no-argument accessors (first, last, anyOne) where there is no index to blame:

(1 to: 10) at: 1     // => 1
(1 to: 10) at: 11    // raises index_out_of_bounds
(1 to: 0) at: 1       // raises index_out_of_bounds (not empty_collection)

Lookups That Find Nothing

A lookup on a non-empty collection can still fail, and each way it fails gets its own kind (BT-3025). None of them is does_not_understand — the receiver understands the selector, so reporting a dispatch failure would send the reader hunting for a typo.

detect: raises not_found when the search runs to completion with no element matching. detect:ifNone: is the non-raising alternative:

#(1, 2, 3) detect: [:x | x > 10]            // raises not_found
#(1, 2, 3) detect: [:x | x > 10] ifNone: [0] // => 0

Every receiver agrees (BT-3028) — List, Set, Bag, Dictionary, Interval, String, and Stream. detect: answers E, and E has no in-band way to say "nothing matched", so the raise is the honest encoding; reach for detect:ifNone: whenever a miss is expected:

#(1, 2, 3) asSet detect: [:x | x > 10]      // raises not_found
(1 to: 3) detect: [:x | x > 10]             // raises not_found
(Stream on: #(1, 2, 3)) detect: [:n | n > 10]  // raises not_found

(1 to: 3) detect: [:x | x > 10] ifNone: [0] // => 0

The error names the receiver's class, so a no-match on a Set reports Set rather than the abstract Collection the shared implementation lives on. An empty receiver is just the degenerate no-match case and raises not_found too, not empty_collection — detect: is a search, not an element accessor.

List from:to: raises index_out_of_bounds for a start index below 1, matching at:. Its other edge cases stay total — an end below the start is an empty range, and an end past the last index is clamped:

#(1, 2, 3) from: 0 to: 2   // raises index_out_of_bounds
#(1, 2, 3) from: 3 to: 1   // => #()  (empty range, not an error)
#(1, 2, 3) from: 2 to: 99  // => #(2, 3)  (clamped)

not_found is a RuntimeError, like empty_collection and index_out_of_bounds, so on: RuntimeError do: catches the whole family and e kind discriminates within it.

Interval — Arithmetic Sequences

An Interval represents an arithmetic sequence of integers without materialising a list. Create one with to: or to:by: on any Integer:

1 to: 10                    // => (1 to: 10) — 10 elements: 1, 2, ..., 10
1 to: 10 by: 2             // => (1 to: 10 by: 2) — 5 elements: 1, 3, 5, 7, 9
10 to: 1 by: -1            // => (10 to: 1 by: -1) — 10 elements: 10, 9, ..., 1

(1 to: 10) size            // => 10
(1 to: 10) first           // => 1
(1 to: 10) last            // => 10
(1 to: 10) at: 5            // => 5 — bounds-checked; out-of-range raises
                             // index_out_of_bounds (see "Accessing an Empty
                             // Collection" above), never empty_collection
(1 to: 10) includes: 5     // => true

// Interval supports the full Collection protocol:
(1 to: 5) inject: 0 into: [:sum :x | sum + x]   // => 15
(1 to: 10) select: [:x | x isEven]              // => #(2, 4, 6, 8, 10)
(1 to: 5) collect: [:x | x * x]                 // => #(1, 4, 9, 16, 25)

A step of 0 raises, and a step or limit that is nil or not a number raises TypeError. An Interval holds integers only, so to:by: also raises TypeError ("Interval step must be an Integer") for a step that is a number but not an Integer, such as 1 to: 2 by: 0.5 or 1 to: 10 by: 2.0 (BT-5217). Likewise to: and to:by: raise TypeError ("Interval limit must be an Integer") for a limit that is not an Integer, such as 1 to: 2.5 (BT-5245); to:do: and to:by:do: still take any number as the limit. In typed code the to:by:do: block parameter is Integer when the start and the step are both statically Integer, and Number otherwise (BT-5246).

The counted loop to:by:do: is not an Interval and takes any Number step: 1 to: 2 by: 0.5 do: [:x | ...] runs with x = 1, 1.5, 2.0. Its block is declared Block(Number, Object), so the type checker treats the loop variable as a Number (BT-5216), except when the start and the step are both statically Integer, where it is an Integer (BT-5246). A step of 0 or 0.0 raises, and a step or limit that is nil or not a number raises TypeError; the compiled counted-loop path raises the same errors. See Control Flow Constructs.

Bag(E) — Multisets

Bag(E) is an unordered collection that allows duplicate elements. It is backed by a Dictionary(E, Integer) mapping elements to occurrence counts. Like other collections, Bag is immutable — mutating operations return a new Bag.

Bag new class                           // => Bag
(Bag new add: 1) occurrencesOf: 1      // => 1

b := Bag withAll: #(1, 2, 1, 3, 1)
b size                                  // => 5 (total occurrences)
b occurrencesOf: 1                      // => 3
b includes: 2                           // => true
b includes: 9                           // => false

// Bag mutating operations return new Bags:
b2 := b add: 2                         // one more occurrence of 2
b2 occurrencesOf: 2                    // => 2
b3 := b add: 4 withCount: 5           // add 5 occurrences of 4
b4 := b remove: 1                      // remove one occurrence of 1
b4 occurrencesOf: 1                    // => 2

// do: iterates each element once per occurrence:
(Bag withAll: #(1, 1, 2)) inject: 0 into: [:sum :x | sum + x]  // => 4

// Bag is unordered, so it has no first/last — use anyOne for a single
// element (no ordering guarantee) or asList first/last for a fixed order:
(Bag withAll: #(1, 1, 2)) anyOne        // => 1 or 2, no ordering guarantee
Bag new anyOne                          // raises empty_collection

Set and Dictionary are unordered the same way and follow the same rule — see "Accessing an Empty Collection" above for the full first/last/anyOne split.

Bag collect:, select: and reject: with a stateful (outer-local–writing) block raise stateful_block_dispatch. Use asList first if you need to filter with side-effects.

Stream — Lazy Pipelines

Stream is Beamtalk's universal interface for sequential data. A single, sealed, closure-based type that unifies collection processing, file I/O, and generators under one protocol.

Operations are either lazy (return a new Stream) or terminal (force evaluation and return a result). Nothing computes until a terminal operation pulls elements through.

Constructors

// Infinite stream starting from a value, incrementing by 1
Stream from: 1                     // 1, 2, 3, 4, ...

// Infinite stream with custom step function
Stream from: 1 by: [:n | n * 2]   // 1, 2, 4, 8, ...

// Stream from a collection (List, String, Set)
Stream on: #(1, 2, 3)             // wraps collection lazily

// Collection shorthand — List, String, and Set respond to `stream`
#(1, 2, 3) stream                  // same as Stream on: #(1, 2, 3)
"hello" stream                     // Stream over characters
(Set new add: 1) stream            // Stream over set elements

// Dictionary iteration — use doWithKey: instead of stream
#{#a => 1} doWithKey: [:k :v | Transcript show: k]

// File streaming — lazy, constant memory
File lines: "data.csv"            // Stream of lines
File open: "data.csv" do: [:handle |
  handle lines take: 10           // block-scoped handle
]

Lazy Operations

Lazy operations return a new Stream without evaluating anything:

MethodDescriptionExample
select:Filter elements matching predicates select: [:n | n > 2]
collect:Transform each elements collect: [:n | n * 10]
reject:Exclude elements matching predicates reject: [:n | n isEven]
drop:Skip first N elementss drop: 5
// Build a pipeline — nothing computes yet
s := Stream from: 1
s := s select: [:n | n isEven]
s := s collect: [:n | n * n]
// s is still a Stream — no values computed

Terminal Operations

Terminal operations force evaluation and return a concrete result:

MethodDescriptionExample
take:First N elements as Lists take: 5 → [2,4,6,8,10]
asListMaterialize entire stream to Lists asList → [1,2,3]
do:Iterate with side effects, return nils do: [:n | Transcript show: n]
inject:into:Fold/reduce with initial values inject: 0 into: [:sum :n | sum + n]
detect:First matching element; raises not_found if nones detect: [:n | n > 10]
detect:ifNone:First matching element, or the default if nones detect: [:n | n > 10] ifNone: [0]
anySatisfy:True if any element matchess anySatisfy: [:n | n > 2]
allSatisfy:True if all elements matchs allSatisfy: [:n | n > 0]
// Terminal forces computation through the pipeline
((Stream from: 1) select: [:n | n isEven]) take: 5
// => [2,4,6,8,10]

(Stream on: #(1, 2, 3, 4)) inject: 0 into: [:sum :n | sum + n]
// => 10

printString — Pipeline Inspection

Stream's printString shows pipeline structure, not values — keeping the REPL inspectable even for lazy data:

(Stream from: 1) printString
// => Stream(from: 1)

(Stream on: #(1, 2, 3)) printString
// => Stream(on: [...])

((Stream from: 1) select: [:n | n isEven]) printString
// => Stream(from: 1) | select: [...]

Eager vs Lazy — The Boundary

Collections keep their eager methods (select:, collect:, do:, etc.) for simple cases. The stream message is the explicit opt-in to lazy evaluation:

// Eager — List methods return a List immediately
#(1, 2, 3, 4, 5) select: [:n | n > 2]
// => [3,4,5]  (a List)

// Lazy — stream methods return a Stream (unevaluated)
(#(1, 2, 3, 4, 5) stream) select: [:n | n > 2]
// => Stream  (unevaluated — call asList or take: to materialize)

The receiver makes the boundary visible: you always know whether you're working with a Collection (eager) or a Stream (lazy).

File Streaming

File lines: returns a lazy Stream of lines — constant memory, safe for large files:

// Read lines lazily
(File lines: "data.csv") do: [:line | Transcript show: line]

// Pipeline composition
(File lines: "app.log") select: [:l | l includes: "ERROR"]

// Block-scoped handle for explicit lifecycle control
File open: "data.csv" do: [:handle |
  handle lines take: 10
]
// handle closed automatically when block exits

Cross-process constraint: File-backed Streams must be consumed by the same process that created them (BEAM file handles are process-local). To pass file data to an actor, materialize first: (File lines: "data.csv") take: 100 returns a List that can be sent safely. Collection-backed Streams have no such restriction.

File I/O and Directory Operations

File provides class methods for reading, writing, and managing files and directories. Both relative and absolute paths are accepted; security relies on OS-level permissions (ADR 0063).

MethodReturnsDescription
File exists: pathBooleanTest if a file exists
File readAll: pathStringRead entire file contents
File writeAll: path contents: textnilWrite text to file (create/overwrite)
File isFile: pathBooleanTest if path is a regular file
File isDirectory: pathBooleanTest if path is a directory
File mkdir: pathnilCreate a directory (parent must exist)
File mkdirAll: pathnilCreate directory and all parents
File listDirectory: pathListList entry names in a directory
File delete: pathnilDelete a file or empty directory
File deleteAll: pathnilRecursively delete a directory tree
File rename: from to: tonilRename/move a file or directory
File absolutePath: pathStringResolve path to absolute
File tempDirectoryStringOS temporary directory path
File open: path mode: modeFileHandleOpen a handle the caller must close
File open: path mode: mode do: blockblock valueBlock-scoped handle, closed on exit
File openHandlesArrayOutstanding open:mode: handles: #[path, mode, owner]
File writeAll: "output.txt" contents: "hello"
File readAll: "output.txt"              // => "hello"
File mkdirAll: "target/data/logs"
File listDirectory: "target/data"       // => ["logs"]
File rename: "output.txt" to: "target/data/output.txt"
File delete: "target/data/output.txt"
File deleteAll: "target/data"

Incremental File I/O — FileHandle

File open:mode: and File open:mode:do: give you a FileHandle for reading and writing against the file's current position, instead of whole-file class methods. This is what an append-only log wants: one open handle, an explicit sync per record.

ModeBehaviour
#readRead only; the file must exist
#writeTruncate or create, write only
#appendCreate if absent; every write lands at end-of-file
#readWriteCreate if absent; existing contents kept

Write-capable modes create missing parent directories.

MethodReturnsDescription
handle read: nBinaryUp to n bytes from the current position
handle readAllBinaryFrom the current position to end-of-file
handle write: datanilWrite a String or Binary
handle writeLine: datanilWrite followed by a newline
handle positionIntegerCurrent byte offset
handle seek: offsetIntegerMove to an absolute offset, returns it
handle flushnilPush buffered writes to the OS
handle syncnilfsync — force data to physical storage
handle closenilClose the handle (idempotent)
handle isOpenBooleanWhether the handle is still open
handle linesStream(String)Lazy lines from the current position

Every method returns a Result except isOpen, which answers a Boolean, and lines, which answers a Stream — with no Result to carry an error, lines raises on a closed or write-only handle instead.

// Block scope — the handle is closed however the block exits
(File open: "events.log" mode: #append do: [:handle |
  handle writeLine: "an event".
  handle sync
]) unwrap

// Caller-owned handle — you close it
handle := (File open: "data.bin" mode: #read) unwrap
(handle seek: 16) unwrap
header := (handle read: 4) unwrap
handle close

Reading past end-of-file is not an error: read: returns a binary shorter than requested, and an empty binary once the handle is at end-of-file.

Closed handles error, they don't crash. Every operation on a closed handle returns a structured Result error:, as does a read on a #write handle or a write on a #read handle:

(File open: "notes.txt" mode: #read do: [:handle |
  handle close.
  handle read: 1        // => Result error: FileHandle 'read:' is closed
]) unwrap

Handles are process-scoped values (HandleScoped(#process)): they can be held across calls but not sent to another actor. The descriptor underneath is a BEAM process, so it keeps working wherever the handle is held on this node — but it does not survive crossing a node boundary.

A handle from open:mode: is yours to close, but you are not the only backstop. Beamtalk registers it against an owner and closes an owner's outstanding handles when the owner dies. The rule is the same under the REPL, beamtalk run, beamtalk test and a release, and whether the send is static (File open: p mode: m) or dynamic (File perform: #open:mode: ...):

  1. At the REPL, the session owns it, so the handle survives from one statement to the next.
  2. Otherwise the calling process owns it — an actor, a supervisor worker, or the plain process a test method or beamtalk run script executes in.

The underlying descriptor lives exactly as long as its owner, no longer and no shorter. File openHandles lists every outstanding handle as #[path, mode, owner] for diagnostics. Still, reach for open:mode:do: whenever a block scope will do — it needs no owner at all.

Open blocks run in your own process. open:do: and open:mode:do: are lowered at the call site (ADR 0109), so only the open itself touches the File class — the block, and the close that follows it, run where you called from. A block may therefore message File again, holds no shared resource, and is under no time limit:

// Fine — the block is running in your process, not inside File
File open: "a.txt" mode: #read do: [:h | File exists: "b.txt"]

Side-Effect Timing ⚠️

Side effects in lazy pipelines run at terminal time, not at definition time:

// This prints NOTHING — the pipeline is just a recipe
s := (Stream on: #(1, 2, 3)) collect: [:n | Transcript show: n. n * 2]

// This is when printing actually happens
s asList
// Transcript shows: 1, 2, 3
// => [2,4,6]

If you need immediate side effects, use the eager collection method (List do:) or call a terminal operation right away.

JsonMapping — Declarative JSON Field Mapping

JsonMapping describes which fields of an object go on the wire, under which key, and through which optional converter block. encode: applies the mapping and answers a Dictionary. Unmapped fields are omitted.

JsonMappable is a protocol: implement class-side jsonMapping -> JsonMapping and asJson is provided. Json generate: finds it through the ordinary asJson hook, so nested mapped objects convert recursively. A hand-written asJson in the class body wins (ADR 0127 §3a).

Value subclass: Issue
  uses: JsonMappable
  field: issueId = ""
  field: title = ""
  field: secret = "x"

  class jsonMapping -> JsonMapping =>
    JsonMapping new
      |> mapField: #issueId to: "issue_id"
      |> mapField: #title

mapField:to:using: takes a converter block for custom encoding. Chain entries with |>, not a cascade — JsonMapping is a Value and a cascade drops every update but the last (ADR 0145). A duplicate key in mapField:to: raises at build time; a field missing from the object raises at encode time. Works on Actors as well as Values.

Rules (BT-5191):

Diagnostic Suppression (@expect)

The @expect directive suppresses a specific category of diagnostic on the immediately following expression. It is a first-class language construct (not a comment) parsed as an expression in any expression list.

@expect dnu
someObject unknownMessage   // DNU hint suppressed

@expect type
42 + "hello"                // type warning suppressed

@expect type
42 unknownMethod            // also suppresses method-not-found (DNU) hints

@expect unused
x := computeSomething       // unused-variable warning suppressed

@expect all
anything                    // any diagnostic suppressed (discouraged — use a specific category)

@expect unresolved_ffi, type
(Erlang some_module) someCall   // suppresses both categories on this one expression

Combined form (BT-3387): A single @expect can list more than one category, separated by commas, to suppress every listed category on the same following expression or declaration — useful when one expression genuinely triggers two independent diagnostics at once (e.g. an FFI call to an unknown module — outside the known-OTP list, the beamtalk_* modules, and the package's own dependency/native modules — whose return type is also inferred as Dynamic). The directive is only reported stale if none of its listed categories match a real diagnostic; if at least one does, the directive is satisfied even though another listed category turned out unnecessary.

Suppression categories:

CategorySuppresses
dnuDoes-not-understand hints
typeType mismatch warnings and method-not-found (DNU) hints
unusedUnused variable warnings
type_annotationMissing or redundant type annotation warnings in typed classes
inheritanceSealed-class/sealed-method constraint errors
class_method_process_resourceA class-side method that runs in the caller's process (ADR 0142) directly creates a resource tied to the caller (ets:new, open_port, link, monitor, timers, …) or acts on the caller (self(), the process dictionary, process_flag) (BT-4302)
cascade_drops_updateA non-final cascade message on a value receiver that answers an updated copy, which the cascade discards (p withX: 5; withY: 10, ADR 0145 § 3, BT-4512)
discarded_updateA non-final statement-level send on a value receiver that answers an updated copy, which is thrown away (p withX: 5. alone, ADR 0145 § 3, BT-4522)
ffi_nested_stringA String nested in a collection argument (List(String), Dictionary keys/values, Tuple) to a stock Erlang call reaches it tagged; an Erlang comparison against raw binaries misses (BT-4243, see Strings at the FFI boundary)
actor_state_abroadA block that touches its actor's state where it runs outside the actor's process (ADR 0137) (lint-only, see below)
dead_assignmentbeamtalk lint's "assignment inside an escaping block" check (lint-only, see below)
lintStyle/redundancy findings: beamtalk lint's unnecessary-parentheses, redundant trailing ^, cascade-candidate, … passes, plus the unreachable-code / shadowed-variable / unattached-doc-comment advisories (lint-only, see below)
allAny diagnostic on the following expression (discouraged — use a specific category)

Not suppressible: no @expect category, not even all, suppresses the error for a misplaced Foo >> sel definition: one whose class is not defined in the same file (ADR 0152), one on a protocol, or an instance-side one on a same-file native: actor (BT-5184). The method would never be compiled, so the file cannot be reported clean.

Lint-only categories (dead_assignment, lint, actor_state_abroad): the diagnostics these suppress are produced only by beamtalk lint's dedicated passes, which beamtalk build/beamtalk test, the LSP, and the REPL never run. Those surfaces therefore leave such a directive alone — neither satisfied nor reported stale — and only beamtalk lint validates it (BT-3384). @expect lint exists for test fixtures that deliberately pin a codegen shape the style lint would otherwise tell you to rewrite (e.g. a trailing ^ whose explicit-return lowering is the thing under test); ordinary code should just take the lint's advice.

@expect type for method-not-found diagnostics:

@expect type suppresses DNU hints unconditionally. A common use-case is type-erasure boundaries where Result.unwrap (or any other method returning Object) causes the type system to lose track of the concrete type:

// Result.unwrap returns Object — the type system cannot verify 'size' exists
@expect type
self assert: someResult unwrap size equals: 10

This is preferred over @expect dnu at type-erasure boundaries because it communicates why the diagnostic appears: a type-system limitation, not intentional dynamic dispatch.

Declaration-level @expect: In addition to suppressing diagnostics on expressions, @expect can be placed before state:/field: declarations and method definitions inside a class body. This suppresses diagnostics that fire on the declaration itself:

typed Object subclass: Collection(E)
  @expect type
  first => (Erlang erlang) hd: self asErlangList   // polymorphic return — suppress missing-annotation warning

Declaration-level @expect supports the same categories, combined-category lists, and stale-directive rules as expression-level @expect.

Unknown categories are parse errors: Writing an unknown category (e.g. @expect selfcapture) is rejected at parse time with an error listing the valid names. This prevents typos from silently suppressing nothing.

Stale directives: If @expect does not suppress any diagnostic (because no matching diagnostic exists on the following expression or declaration), the compiler emits a warning to prevent directives from silently becoming out of date.

@expect works inside method bodies, inside block bodies (e.g., ifTrue: [...], collect: [...], whileTrue: [...]), on declarations in class definitions, inside Protocol define: bodies (above a provided method, to suppress a provision diagnostic published in the protocol file — beamtalk build and beamtalk lint only; BT-3671), and at module scope (BT-2010).

Where @expect is evaluated (BT-2851): @expect directives are matched and applied by a single function, apply_expect_directives, called at the end of both diagnostic pipelines:

"Stale" means: for a given @expect directive, this specific diagnostic run produced no diagnostic of a matching category whose span falls inside the annotated expression or declaration. Both pipelines share the same semantic-analysis entry points and the same matching logic, so a diagnostic that either surface can produce is treated identically by both — an @expect is not stale on one surface and legitimate on the other for the same diagnostic.

This includes Erlang FFI argument-type diagnostics (@expect type on a call like Erlang lists reverse: 42): both beamtalk lint and beamtalk build/beamtalk test type-check FFI calls against the same native-type registry, populated by the same extractor (extract_type_specs) from OTP/dependency .beam files. Earlier, lint read that registry only from an on-disk cache (_build/type_cache/) written by a previous beamtalk build; on a project that had never been built, the cache read returned nothing, lint silently skipped the FFI argument-type check, and any @expect type added to suppress the corresponding build-time diagnostic was then reported "stale @expect" by lint. Lint now calls the same live extractor build does — which still reads the on-disk cache as a fast path when it is fresh — so both surfaces populate the registry identically regardless of build order.

Pragma Annotations (@primitive and @intrinsic)

The standard library uses pragma annotations to declare methods whose implementations are provided by the compiler or runtime rather than written in Beamtalk code.

There are two pragma forms:

PragmaSyntaxPurpose
@primitiveBare (no selector)Selector-based dispatch, selector inferred from the enclosing method. Equivalent to @primitive 'sel' where sel is the method's own selector. Preferred form.
@primitive 'selector'Quoted selectorSame selector-based dispatch, but with an explicit selector override — used when the runtime function name differs from the method selector (e.g. class-side aliases like signal => @primitive 'classSignal').
@intrinsic nameUnquoted identifierStructural intrinsic — the compiler generates specialized code inline. Used for spawning, block evaluation, control flow, reflection, etc.

Both forms are semantically equivalent at the compiler level (they produce the same AST node), but the naming convention distinguishes their intent:

@primitive (bare or quoted) — runtime-dispatched method implementations. A bare @primitive infers its selector from the method, so the explicit string is only needed for genuine renames:

// In stdlib/src/integer.bt — bare form, selector inferred ('+' and 'asString')
+ other => @primitive
asString => @primitive

// In stdlib/src/exception.bt — explicit override (method 'signal' → runtime 'classSignal')
class signal => @primitive 'classSignal'

no_user_code (stdlib only). A selector-based @primitive may end with the word no_user_code on the same line. It promises the primitive never runs user code for any argument, so the compiler can skip the state-threading bracket around the call in an actor method (ADR 0137 §4):

// In stdlib/src/list.bt
size -> Integer => @primitive no_user_code
isEmpty -> Boolean => @primitive no_user_code

The promise is checked when the stdlib is built (beamtalk build-stdlib fails on a bad mark): the class must be sealed, the pragma selector-based (not @intrinsic, not an explicit quoted selector), and every parameter a primitive type or a sealed value type (a block or an open class could run user code). It is for stdlib authors; stdlib/src/ is its only use, and the stdlib tests run through it. See actor-state-cell.md.

@intrinsic (unquoted) — compiler structural intrinsics:

// In stdlib/src/block.bt
value => @intrinsic blockValue
whileTrue: bodyBlock => @intrinsic whileTrue

// In stdlib/src/object.bt
new => @intrinsic basicNew
hash => @intrinsic hash

The full list of structural intrinsics: blockValue, blockValue1–blockValue3, whileTrue, whileFalse, unaryWhileTrue, unaryWhileFalse, repeat, onDo, ensure, timesRepeat, toDo, toByDo, basicNew, basicNewWith, hash, respondsTo, fieldNames, fieldAt, fieldAtPut, dynamicSend, dynamicSendWithArgs, error.

Actor>>spawn/spawnWith: (BT-3072). Unlike the intrinsics above, spawn/spawnWith: are not @intrinsic — actor.bt declares real FFI bodies ((Erlang beamtalk_actor_ffi) doSpawn: self). The compiler's static Counter spawn / self spawn call sites still lower directly to beamtalk_actor:safe_spawn/class_self_spawn (unchanged, to avoid serializing every spawn through the class gen_server) — the declared body is the documented source of behaviour for the dynamic dispatch path, mirroring spawnAs:/spawnWith:as:'s existing FFI-body shape. See stdlib/src/actor.bt.

Actor>>new/new: (BT-3074). Also not @intrinsic — actor.bt declares real bodies that send Exception signalKind:class:selector:hint: (BT-3042), the general-purpose pure-Beamtalk way to raise a named error kind with a hint. class_send intercepts new/new: before class-method dispatch ever reaches these declarations (routing instead to the compiled per-actor-module new/0/new/1 stub the runtime's {new, Args} fast path requires), so this is purely the documented, xref-visible source for the selector — never the code path an actual send executes. The type checker correctly proves these bodies diverge via the class-side keyword send to Exception signalKind:class:selector:hint: (BT-3075 unified the type-string resolver).

Relationship to native: (ADR 0101). @primitive and @intrinsic cover native BEAM value types and compiler substrate. A third mechanism, the class-level native: declaration with => self delegate bodies, covers whole-class delegation to a single Erlang module (a stateless Object such as Stream, or an Actor gen_server). Pick by what the method needs: guarded dispatch → @primitive; the dispatch act itself (==, class, perform:, actor lifecycle) → @intrinsic; pure pass-through to one module → native:. See native: for stateless Objects.

whileTrue:/whileFalse:/repeat/on:do:/ensure: via perform: (BT-2908). These five structural intrinsics have real semantics only at the call-site interception the compiler recognizes for a literal message send (e.g. [cond] whileTrue: [body] written directly in source). Reaching the compiled method body through any other dispatch path — perform:, perform:withArguments:, or other generic/dynamic sends — used to resolve to a placeholder and raise a misleading does_not_understand naming the wrong (internal) selector. This is now handled the same way BT-2812/BT-2888 handle it for value*/do:/collect:/etc.: a Tier 1 (pure) condition/receiver/handler/cleanup block gets a real generic implementation — a runtime loop for whileTrue:/whileFalse:/repeat, a runtime try/catch for on:do:/ensure: — since neither needs the block's literal AST, only its (opaque, already-evaluated) fun value. A Tier 2 (stateful, ADR-0041) block reached this way raises a clear #stateful_block_dispatch error instead, since a generically-dispatched call site has no live StateAcc to thread mutations through. respondsTo: returns true for these selectors either way, since the method genuinely is defined.


Ets — Shared In-Memory Tables

Ets wraps OTP ets tables: either shared between actors without message-passing overhead, or private to one actor.

ConstructorNameWho may read / writeUse for
Ets new: #name type: tnode-globalany process / any processState shared between actors
Ets newOrExisting: #name type: tnode-globalany process / any processShared state that may already exist
Ets private: tnoneowner only / owner onlyOne actor's internal state, secrets
Ets protected: tnoneany process / owner onlyOne writer, many concurrent readers

Creating a Table

// Create a named public table
cache := Ets new: #myCache type: #set

// Table types
Ets new: #t1 type: #set          // one entry per key (unordered)
Ets new: #t2 type: #orderedSet   // one entry per key (sorted keys)
Ets new: #t3 type: #bag          // multiple entries per key, values differ
Ets new: #t4 type: #duplicateBag // multiple identical entries per key

// Look up an existing named table from another actor
cache := Ets named: #myCache

// Unnamed tables, owned by the caller
secrets := Ets private: #set      // only this process may use it
board := Ets protected: #set      // others may read, only this process writes

A named table's name is global to the node, so a second instance of the same actor cannot create the same name again (already_exists). Unnamed tables avoid that: create one per actor in initialize and keep it in a field typed :: Ets. They have no name, so Ets named: cannot find them. Using one from a process its protection forbids, or calling delete from any process but the owner, raises access_denied, not a raw badarg. Each REPL input runs in a short-lived process, so an unnamed table created at the REPL is deleted when that input finishes; create it in the actor that uses it. Printing or inspecting an Ets never shows its entries.

Actor subclass: SessionStore
  state: table :: Ets

  initialize -> Nil =>
    self.table := Ets private: #set
    nil

  remember: id state: s => self.table at: id put: s
  claim: id => self.table removeKey: id ifAbsent: [nil]

Reading and Writing

cache at: "key" put: 42         // insert or update
cache at: "key"                 // => 42
cache at: "missing"             // => nil (not an error)
cache at: "missing" ifAbsent: [0]  // => 0 (evaluate block when absent)
cache at: "key" ifPresent: [:v | v + 1]  // => 43 (evaluate block if present; nil if absent)
cache at: "key" ifPresent: [:v | v * 10] ifAbsent: [0]  // => 420 (one lookup; a stored nil is present)
cache includesKey: "key"        // => true
cache includesKey: "other"      // => false
cache includes: 42              // => true (scan values)

Iteration and Snapshots

Ets conforms to Enumerable(V), so collection messages work over a point-in-time snapshot of values:

cache do: [:v | Transcript show: v]
cache select: [:v | v > 10]     // => List of matching values
cache collect: [:v | v * 2]     // => List of transformed values

// Key/value iteration (doWithKey: is an alias of keysAndValuesDo:)
cache keysAndValuesDo: [:k :v | Transcript show: k, ' => ', v]
cache doWithKey: [:k :v | Transcript show: k]

// Snapshot to Dictionary
d := cache asDictionary          // => Dictionary(K, V)

// Snapshot values to List
vs := cache values               // => List(V)

Atomic Operations

For #set and #orderedSet tables only (raises unsupported_table_type on bag tables):

cache at: "hits" increment: 1   // atomic add via ets:update_counter; missing key starts at 0
cache at: "key" update: [:v | (v ifNil: [0]) + 1]  // atomic read-modify-write (CAS loop)

at:update: runs an optimistic compare-and-swap loop: the block receives the current value (nil if missing) and must be side-effect-free, since it may run more than once under contention.

Other Operations

cache size                      // => number of entries
cache isEmpty                   // => true if no entries
cache isNotEmpty                // => true if at least one entry
cache keys                      // => List of all keys (order unspecified for #set)
cache removeKey: "key"          // delete entry; no-op if key is absent
cache removeKey: "key" ifAbsent: [nil]  // atomically remove and answer the value (ets:take)
cache removeAll                 // remove all entries, keep the table
cache delete                    // destroy the table; frees all memory

Cross-Actor Sharing

Tables made with new:type: are process-owned but publicly readable and writable. Create a named table in one actor, then retrieve it from another:

// Actor A — create the table
cache := Ets new: #requestCache type: #set
cache at: "token" put: "abc123"

// Actor B — retrieve by name
cache := Ets named: #requestCache
cache at: "token"               // => "abc123"

Table Lifecycle

The owning process (the one that called Ets new:type:, private: or protected:) holds the table. When that process terminates, the table is automatically deleted by the OTP runtime. Only the owning actor should call delete on the table — other actors should request deletion by messaging the owner. A named table is public, so ETS does not stop another process deleting it; a private:/protected: table raises access_denied on a delete from any process but the owner. A delete of a table that is already gone raises stale_table, for named and unnamed tables alike. Call delete explicitly in the owner to release memory before the process exits.


Queue — O(1) Amortised FIFO Queue

Queue wraps Erlang's :queue module, providing O(1) amortised enqueue and dequeue. It is a value type: each mutation returns a new Queue rather than modifying the receiver. Use Queue instead of List when O(1) amortised head/tail access matters.

Creating a Queue

q := Queue new        // empty queue

Enqueueing and Dequeueing

q2 := q enqueue: 1
q3 := q2 enqueue: 2
result := q3 dequeue         // => {1, <Queue with [2]>}
value := result at: 1       // => 1
rest := result at: 2        // => Queue containing [2]

dequeue returns a Tuple of {value, newQueue}. Raises empty_queue if the queue is empty.

Other Operations

q peek                        // => front element without removing (raises empty_queue if empty)
q isEmpty                     // => true or false
q size                        // => number of elements (O(n))

AtomicCounter — Lock-Free Shared Counter

AtomicCounter provides a named integer counter backed by ets:update_counter. Increments and decrements are atomic and safe for concurrent access from multiple actors without message-passing overhead.

Creating a Counter

c := AtomicCounter new: #requests     // create named counter starting at 0
c := AtomicCounter named: #requests   // look up existing counter from another actor

Atomic Operations

c increment                    // atomically add 1, return new value
c incrementBy: 5               // atomically add N, return new value
c decrement                    // atomically subtract 1, return new value
c decrementBy: 3               // atomically subtract N, return new value
c value                        // instantaneous read; may observe a stale value under concurrent updates or reset
c reset                        // set to 0, return nil (not atomic with concurrent increments/decrements)
c delete                       // destroy the backing ETS table

Cross-Actor Sharing

// Actor A — create
c := AtomicCounter new: #hits

// Actor B — look up by name and increment
c := AtomicCounter named: #hits
c increment

Counter Lifecycle

Each AtomicCounter owns its own named ETS table. When delete is called, the table is destroyed and the counter is stale. Any subsequent operations on a deleted counter raise stale_counter.


TestCase — BUnit Testing

TestCase is a Value subclass: — setUp returns a new self with fields set (functional pattern), matching Erlang's EUnit and Elixir's ExUnit. The test runner threads the setUp return value to each test method. Each test gets a fresh copy, so tests cannot corrupt state for each other.

TestCase subclass: CounterTest
  field: counter = nil

  setUp => self.counter := Counter spawn

  testIncrement =>
    self.counter increment.
    self assert: (self.counter getValue) equals: 1

For multiple fields, chain the assignments — the LAST statement is what the runner threads through as self:

TestCase subclass: IntegrationTest
  field: db = nil
  field: cache = nil

  setUp =>
    self.db := DB connect
    self.cache := Cache spawn

  testLookup =>
    self.cache at: "key" put: "value".
    self assert: (self.cache at: "key") equals: "value"

Key points:

Any statement after the last self.field := value silently drops that field (BT-3391) — setUp's return value is always its last expression's value, and only a trailing field assignment (or bare self) evaluates to the updated self. Adding one more line after your last assignment — a super setUp call, a log line, an unrelated local — makes setUp return THAT statement's value instead, and every field set above it reads back as its default in every test method, with no compile or runtime error:

setUp =>
  self.db := DB connect
  self.cache := Cache spawn
  Transcript show: "set up".   // <- adding this line breaks self.db and self.cache!

Fix it by ending with an explicit trailing self:

setUp =>
  self.db := DB connect
  self.cache := Cache spawn
  Transcript show: "set up".
  self   // <- carries both field mutations forward

beamtalk build/beamtalk lint warn when a setUp mutates a field — via self.field := value or a with<Field>: send — and its last statement isn't a bare self, another field assignment, a with<Field>: send (or a chain of them, nested or written as a |> pipeline), or a cascade on self whose only with<Field>: message is its last.

A cascade on self with more than one with<Field>: message does not return the updated self either (ADR 0145). A cascade sends every message to the original receiver, so on a value each with*: returns its own copy and the cascade's value is the last message's result alone — every with*: before the last is silently dropped. The general cascade-drops-update warning reports this at each dropped message (here, withCounter:), so the setUp check adds no second warning of its own for this shape — also when setUp ends in a local bound to such a cascade (BT-4573). One @expect cascade_drops_update on the statement silences it. If cascade-drops-update cannot prove every dropped message (for example, one is a hand-written with*: method with no -> Self return annotation), the setUp warning above still fires. Turning cascade-drops-update off under [diagnostics] opts the project into fan-out cascades on values, so this shape then gets no warning at all. Chain the sends with a pipeline instead, so each one applies to the previous result:

// Wrong — `self withCounter: 1; withDb: 2` keeps only `db`; `counter` stays at its default
setUp => self withCounter: 1; withDb: 2

// Right — each send receives the copy the previous one returned
setUp => self withCounter: 1 |> withDb: 2

// Also right — the nested form the pipeline stands for
setUp => (self withCounter: 1) withDb: 2

Chained with*: setters (self withCounter: (Counter spawn)) remain a valid alternative to self.field := value — each with*: call itself returns the fully updated self, so the chain's own last call already carries every field set through. This only holds when the with*: chain is itself the trailing statement of setUp: like a bare self.field := value, its self-preserving return value only threads through when nothing follows it — the same trap applies, and beamtalk lint (BT-3391/BT-3395) warns for both forms.

Suite-Level Setup — setUpOnce / tearDownOnce

For expensive fixtures shared across all tests in a class (database connections, ETS tables, supervisor trees), override setUpOnce and tearDownOnce. These run once per class, not once per test.

setUpOnce returns a fixture value accessible in each test method via self suiteFixture:

TestCase subclass: DatabaseTest
  field: conn = nil

  setUpOnce => Database connect: "test_db"
  tearDownOnce => self suiteFixture close

  setUp => self withConn: self suiteFixture

  testQuery =>
    result := self.conn query: "SELECT 1"
    self assert: result equals: 1

  testInsert =>
    self.conn execute: "INSERT INTO t VALUES (1)"
    self assert: (self.conn query: "SELECT count(*) FROM t") equals: 1

Lifecycle order: setUpOnce → (setUp → test → tearDown)* → tearDownOnce

Key points:

Shared Tests — Abstract Test Cases

To run one list of tests against several subjects, write the tests once on an abstract TestCase subclass with a hook the subclasses answer, and give each subject a concrete subclass. A test class runs its own test* methods and those it inherits from every superclass below TestCase (as well as an inherited setUp/tearDown/setUpOnce/tearDownOnce); an abstract test class is never run itself.

// stdlib/test/fixtures/stack_contract_test.bt
abstract TestCase subclass: StackContractTest
  subject => self subclassResponsibility

  testPushPop =>
    s := self subject new
    s push: 1
    self assert: s pop equals: 1

// stdlib/test/list_stack_test.bt
StackContractTest subclass: ListStackTest
  subject => ListStack

Put the abstract class under fixtures/ (fixtures are compiled for every test file, so the subclasses in other test files can name it as their superclass).

Parallel Test Execution

By default, beamtalk test runs test classes concurrently (--jobs 0 = auto, uses BEAM scheduler count). Each class runs in its own process.

Test classes that touch global state (persistent_term, registered process names, global ETS tables) must opt out by overriding serial:

TestCase subclass: TracingTest

  class serial -> Boolean => true

  setUp => Tracing clear. Tracing disable
  testEnable => self assert: Tracing enable equals: nil

Serial classes run alone after all concurrent classes complete.

Use --jobs 1 for fully sequential execution, or --jobs N to limit concurrency.

From the REPL, use TestRunner runAll: maxJobs to control concurrency programmatically:

TestRunner runAll: 4        // run up to 4 classes concurrently
TestRunner runAll            // sequential (default from REPL)

See Tooling for CLI tools, REPL, VS Code extension, and testing framework.