ADR 0152: Remove Cross-File Extension Methods

Status

Accepted (2026-11-24)

This supersedes the cross-file part of ADR 0066: a Class >> selector => ... definition in a file that does not define Class. Superseded: §2 (the Class+Feature.bt file convention), §3 (ETS dispatch with interleaved lookup), §4 (compile-time conflict detection and type metadata), §6 (load order), §7 (ETS table lifecycle), and the BT-5002, BT-5060 and BT-5061 lookup-order amendments. Also superseded: §5 (sealed classes can be extended), because neither remaining form of >> can reach a stdlib class. Kept: the >> syntax (§1) for same-file methods and for live method definition, and the >> reflection operator.

The first draft of this ADR proposed replacing cross-file >> with retroactive protocol implementations (Proto implementFor: Class). The owner decided to remove first and defer the replacement until a concrete need appears, and to remove without a deprecation period, because no package uses the feature. That design is kept under Future direction.

How to read the evidence. A claim marked (read) was checked by reading the cited code on main at 9dcf825. A claim marked (inferred) follows from that reading but was not checked directly. A claim marked (reviewer) was reported by an adversarial review pass and spot-checked, not read in full. Nothing in this ADR was verified by running the system.

Context

Problem statement

Beamtalk has one way to add a method to a class from outside the class's file: the cross-file extension method of ADR 0066.

// In helpers.bt. String is defined in stdlib, not in this file.
String >> shout => self uppercase ++ "!"

The compiler registers the method in a runtime table when the declaring module loads, and every lookup consults that table at each level of the superclass walk. The mechanism has three problems.

1. It is almost unused. A count of top-level Class >> selector => definitions whose target class is not defined in the same file:

WhereCross-file extensions
stdlib/src0 (read)
examples/0 (read)
buccaneer, catalina, http, oauth, mint, hpack, yaml, linear, agents, announcements (about 400 .bt files)0 (reported by the owner's survey; not re-checked here)
beamtalk-symphony (48 .bt files), beamtalk-exdura (92)0. Every >> is a Class>>selector reference in a comment (checked by the parent session, and by gh api search/code here)
beamtalk-watcher, beamtalk-collections0. Same comment-only pattern in the search fragments returned (code search shows a few fragments per file, so this is strong but not exhaustive)
beamtalk-liquid (32 .bt files), beamtalk-registry0 hits for >> in .bt files (liquid also checked by the parent session). With liquid, every dependency of symphony and exdura is covered
beamtalk-uat1 file: a UAT fixture with SomeActor >> bumpBy: and SomeActor >> tallyPlusTen, written to exercise the feature (BT-2452)
stdlib/test11 files, 16 target classes (read)
tests/parity3 files (read)
tests/repl-protocol/cases0 cross-file definitions. Five scripts type Foo >> sel at the prompt for a class defined earlier, which is a live edit, a refusal test or a same-file case, not a cross-file extension. Five other scripts call beamtalk_extensions through FFI (reviewer, spot-checked)
benchmarks/, test-package-compiler/casesbenchmarks/vs-elixir/beamtalk/src/vb_shadowed_math_ext.bt (BT-4431) and the foreign_extension and set_theoretic_operators snapshot cases: fixtures written to measure or snapshot the feature (reviewer, spot-checked)
fuzz/corpus0 definitions. The one >> file uses the Counter >> #sel reflection form (read)

Every use is a test of the feature itself. No package uses it to do work.

2. It is expensive to keep.

3. Its lookup order is a steady source of bugs. The order is: the receiver's own compiled method, then at each ancestor that ancestor's extension before its compiled method. The class side differs: an extension beats the class's own compiled method (BT-5061). A Linear search for "extension" over the last 90 days returns 55 issues. A handful are about the VS Code extension; most of the rest are lookup-order or precedence bugs:

IssueWhat went wrong
BT-5002An extension on Actor was ignored more than one level below Actor
BT-5060An extension on a Value class is ignored by a direct subclass for a selector the class compiles (the "one-hop gap"; assessed and left as a warning)
BT-5061Class-side extension beats the class's own compiled class method, the opposite of the instance side
BT-5062removeSelector: on an owner that also has an extension
BT-4307Class-side extensions on an ancestor not reached through a subclass
BT-4588new / new: ignored an ancestor's class-side extension
BT-4250Class-side super consulted the wrong class's extension
BT-4133Class-side extensions bypassed by direct-called methods
BT-3951A runtime extension overriding a known collection selector defeated a codegen guard

Tooling carried the same cost: the WS3 epic (BT-4610, with BT-4608 and BT-4611) made dependency extensions visible to consumers, and BT-4658 and BT-4923 found validators that skipped extension bodies.

Not every extension bug is a precedence bug. BT-4503 (a value-type extension with ^ in a block answered {Result, Self}) and BT-3920 were bugs in how extension bodies are compiled, and this ADR keeps that body codegen (see Consequences).

The precedence bugs share one root. An extension can take precedence over a compiled method, so every dispatch path, static call, cache and tool must ask "is there an extension that wins here?" The BT-5060 work that merged as #5718 is the latest instance: it adds warning plumbing through eval, load and sync replies to tell the user about a case the dispatch order cannot honour.

What >> is actually used for

>> has three uses, and only one of them needs the extension table.

So the first two uses already work without the extension table.

The REPL and the build already disagree

A cross-file extension works only in a module built by beamtalk build, test or run. In a workspace it does not (read):

So the same file means different things under beamtalk run and in the REPL, which docs/beamtalk-principles.md §4 forbids. The one path the first draft did not check is real (read, Phase 0): workspace startup activates BEAMs that the CLI built earlier. beamtalk_workspace_bootstrap:activate_project_modules/1 loads _build/dev/ebin and activate_dependency_modules/1 loads _build/deps/*/ebin, through beamtalk_module_activation, which calls each module's register_class/0. A module built by an older compiler therefore registers its cross-file extensions in a workspace, while the same source loaded with Workspace load: drops them. After Phase 1 no build can produce such a module, and the build stamp (Phase 2) forces a rebuild of any older one, so this path closes without extra work.

What is lost

Two things, and the decision has to own both.

Constraints

Decision

Cross-file extension methods are removed. A Class >> selector => ... or Class class >> selector => ... definition is valid only where the class's source is at hand: in the file that defines the class, or as a live edit of a class whose source the workspace holds.

1. What stays and what goes

FormAfter this ADR
Foo >> sel => ... in the file that defines FooUnchanged. Folded into the class (BT-4721).
Foo >> sel => ... and Foo class >> sel => ... at the REPLUnchanged. Recompiles the class from its stored source and hot-loads it.
Class compile: #sel source: "...", IDE and MCP save_methodUnchanged. Same recompile path.
Proto >> sel => ... at the REPL (ADR 0127 §11)Unchanged. Patches the provision and re-expands users.
The >> reflection operator, Foo >> #sel, which answers a CompiledMethodUnchanged. Only >> as a cross-file method definition is removed. Code built on the operator, such as exdura's self runActivity: OrderActivities >> #reserveInventory:, is not affected
Foo >> sel => ... in a file that does not define Foo, including another file of the same packageRemoved. A compile error.
pkg@Foo >> sel => ... (ADR 0070)Removed with it.
beamtalk_extensions:register/4,5 called through FFIRemoved. The module is deleted.
// money.bt — still valid: Money is defined in this file
Value subclass: Money
  field: cents = 0

Money >> isZero => self.cents = 0
// helpers.bt — a compile error after this ADR
String >> shout => self uppercase ++ "!"
error: `String >> shout` adds a method to String, which is not defined in this file.
  = cross-file extension methods were removed (ADR 0152).
  hint: define the method in the file that defines the class (in the class
        body, or as `String >> shout` next to it), or, for a class loaded in
        a workspace, define it live from the REPL or the IDE.
        For a class you cannot edit, write a method on a class of your own
        that takes the String.

At the REPL, a live definition on a class with source works as before:

>> Counter >> incrementBy: n => self.value := self.value + n
>> c incrementBy: 5
=> 6

A live definition on a class without stored source already fails, with "Class source not available for Integer" (beamtalk_repl_loader.erl:241-246), and Class compile:source: refuses a stdlib class outright (beamtalk_repl_eval.erl:1062-1073) (read; not run). So Integer >> double => self * 2, the REPL example in ADR 0066 §1, fails today as far as the code shows. This ADR does not change that behaviour.

There is no deprecation period. Workspace load: of a file with a cross-file >>, and an inline REPL eval that mixes a class definition with a foreign X >> m, today drop the method with a warning (Context). Both now fail with the compile error above. These are changes to REPL output, made by this decision.

2. Lookup order after removal

  1. The receiver's class: its compiled method.
  2. Each ancestor in turn: its compiled method.
  3. doesNotUnderstand:args:.

The class side follows the same order over class methods.

"Compiled method" here includes the methods a class was given as runtime funs, which this ADR does not touch: ClassBuilder method funs and put_method/3 on the instance side (beamtalk_object_class.erl:671) (reviewer), and ADR 0084 class-method funs on the class side, which are checked before that class's compiled class methods (put_class_method, beamtalk_object_class.erl:691) (read). They belong to the class and are installed through it.

There is no extension step at any level, on either side. The BT-5060 one-hop gap disappears because there is nothing to skip. respondsTo:, canUnderstand:, perform: and super follow the same order because they have nothing else to consult.

The guarantee, once the runtime pieces are deleted (Phase 2). Loading a package cannot change which method answers a send to an existing class. Between Phase 1 and Phase 2 the table still exists, but nothing the compiler accepts can fill it; only an FFI call or a module built by an older compiler can.

3. What is deleted

The full list, with files, is in Implementation. In summary:

What stays: same_file_fold.rs; the REPL and IDE recompile path; StandaloneMethodDefinition in the AST (the same-file and live forms parse to it); the class-derived cache and its generation read, which hot reload still needs (BT-4984 kept that read partly for extensions; this removes one reason for it, not the read); ADR 0084 runtime funs.

4. Patching a running class

What the code supports today, and so what remains:

TargetInstance methodClass method
Class with source in the workspaceFoo >> sel => ... at the REPL (install_method_with_source, beamtalk_repl_loader.erl:265); Class compile:source:; MCP and IDE save_method (install_method/9, beamtalk_repl_loader_methods.erl:85-171). All recompile the class and hot-load it (read)Foo class >> sel => ... at the REPL, the same path with is_class_method = true (beamtalk_repl_loader.erl:268-279) (read). Not reachable from MCP save_method or Class compile:source:: classCompileSource/3 calls compile_method/6, which is instance side only (beamtalk_repl_eval.erl:1041-1042), and SaveMethodParams has no side field (read)
Stdlib classRefused: "built-in methods are read-only in the workspace" (stdlib_method_read_only_error, beamtalk_repl_eval.erl:1238) (read)Refused the same way
Dependency classFails: no class source is stored for a dependency (activate_dependency_modules registers the module and source path only, beamtalk_workspace_bootstrap.erl:121-128) (read)Fails the same way

So the REPL and IDE path covers every class the workspace has source for, on both sides at the REPL and on the instance side from the IDE and MCP. That is unchanged.

For the last two rows, a cross-file extension was the only way to add or replace a method, and only from a rebuilt module, not from a workspace load (Context). ADR 0066 kept the class-side "extension first" order (BT-5061) because a class-side extension was "the documented way to patch a class method of a running class" (ADR 0066 §3), and BT-4133, BT-3700, BT-4270, BT-4301, BT-4316 and BT-4317 built the shadow flags and static call keys to honour it.

After this ADR, a class method of a class without stored source is changed by rebuilding and redeploying the class's package. An ADR 0084 runtime class-method fun still takes precedence over a compiled class method, but it has no user-level entry point for an existing class: put_class_method is reached only from the class process, and ClassBuilder's addClassMethod: applies while a class is being built (stdlib/src/class_builder.bt:293) (reviewer). It is not offered as a workaround.

What is actually lost is therefore small: shipping a patch to someone else's class method inside your own package's build. Getting it onto a running node already took a rebuild. This is Open Question 1, and the implementation proceeds on its default.

5. What to do instead, until there is a replacement

Single source of truth

Prior Art

LanguageCan outside code add a method to a class or type?Notes
Pharo, SqueakYes, *Package extension protocolsLast loaded wins. Overrides are a known packaging problem
RubyYes, open classesLast definition wins. Refinements (lexical) are not seen by respond_to?
Objective-CYes, categoriesUndefined which implementation runs on a clash (Apple QA1908)
SwiftYes, extensions; retroactive conformance warns since SE-0364Resolved statically for non-protocol members
Kotlin, C#Yes, but statically resolved and lexically scopedThe member always wins, silently
ElixirOnly through a protocol: defimpl P, for: TReached as P.fun(x); nothing enters the type's own functions
RustOnly through a trait, under the orphan rule (RFC 2451)No inherent methods on a foreign type
GoNo. Methods may be declared only on types defined in the same packageThe idiom is a function or a local wrapper type (from memory, not searched)
NewspeakNoNo global namespace to extend
Gleam, ErlangNoFunctions in your own module
PythonNot for built-in typesUser classes can be patched; str and int cannot (from memory, not searched)

After this ADR Beamtalk sits with Go, Newspeak, Gleam and Erlang: a class's methods are defined with the class. That is a departure from Pharo, taken for the reason ADR 0066 itself gave for rejecting Pharo's last-writer-wins: a package ecosystem is not one developer's image.

The languages that allow outside additions and keep them sound (Rust, Elixir) do it through a protocol or trait with rules about who may implement it. That is the shape of the Future direction.

User Impact

Newcomer. One fewer feature to learn, and one fewer way for a method to appear from nowhere. Someone coming from Ruby or Kotlin will try String >> shout in a helper file and get an error that says what to write instead.

Smalltalk developer. This is a real departure: Pharo developers extend Object and String freely. What stays is the part of the Smalltalk experience Beamtalk actually exercises: redefine a method on a live class from the REPL or the browser and see it take effect.

Erlang/BEAM developer. A class is its module again. To find what answers a send, read the class and its superclasses; there is no table to consult. Generated dispatch loses its extension probes.

Production operator. Loading a package cannot change the behaviour of an existing class. The cost: a class method of a deployed class without source can no longer be replaced from a file (Decision §4).

Tooling developer. No secondary index for extension locations, no "extensions" group, no dependency-extension channel, and no dependency_extensions_unknown guard in the type checker.

Steelman Analysis

Keep ADR 0066 open classes

Additive-only >> (keep the syntax, forbid overriding)

Replace now with protocol implementations (implementFor:)

Pure protocol dispatch (Elixir): Json encode: x

Tension points

Alternatives Considered

Keep ADR 0066 open classes as they are

Rejected. The feature has no users outside its own tests, about 52 Erlang and 111 Rust files carry it, and its lookup order has produced about nine precedence bugs in 90 days, the last of which (BT-5060) was closed by adding warnings instead of fixing the order. The cost recurs with every new dispatch optimisation, because each one must prove that no extension outranks the method it resolved.

Additive-only >> without protocols

Keep the cross-file syntax, make a clash with a compiled method an error, and consult the table only on a miss.

// app/src/Money+Json.bt
Money >> asJson => self class jsonMapping encode: self
Money class >> jsonMapping => JsonMapping new |> mapField: #cents to: "amount"

This removes the precedence bugs and keeps the capability. Compared with removal and with the deferred design:

Remove (this ADR)Additive-only >>implementFor: (deferred)
Precedence bugs removedYesYesYes
Extension table on the dispatch pathNoneOn a miss onlyOn a miss only
Registration, load order, clash handling at run timeNoneNeededNeeded
Add a method to a foreign classNoYesYes
Ceremony for one methodn/aNoneA protocol
Provided methods come with the protocoln/aNo; each is written out againYes
Something to attach an ownership rule ton/aNoYes
WS3 dependency plumbingDeletedKeptKept, as declarations

Rejected for now, on cost: it keeps a runtime table, a registration protocol and the dependency plumbing alive for a feature with no users. It is not rejected for being a worse design than implementFor:; the table above shows the two need the same runtime machinery. It stays on the list: if a need appears and the owner concludes that ownership rules are not worth their ceremony, this is the smaller of the two replacements, and nothing in the miss-only runtime design depends on which syntax fills the table.

Replace now with protocol implementations

The first draft of this ADR. Add Proto implementFor: Class, then deprecate and remove cross-file >>. Rejected by the owner in favour of removing first, for three reasons: nothing uses the feature being replaced; the ownership rule at the centre of the design cannot be settled without a real case (see Future direction, F3); and the replacement is an XL piece of work whose only demonstrated use is asJson. The design is kept below.

Pure protocol dispatch: Json encode: x, nothing enters the class's lookup

Implementations are keyed by {protocol, class} and reached only through the protocol: JsonRepresentable asJson: x, or a facade such as Json encode: x.

This is the cleanest design at run time and the only one where an ownership rule is fully sound. It is not needed for removal, so the question is whether it should be the future direction instead of implementFor:. It was weighed seriously and is not preferred, because:

What implementFor: gives up in return is real: coherence is by {class, selector}, so its ownership rule is weaker than Rust's (F3). Because this ADR only removes, the choice between the two stays open until a real case arrives, and a library is free to offer Json encode: x-style entry points today.

Lexically scoped static extension functions (Kotlin, C#)

x shout resolves at compile time, from the static type of x, to a function imported into the file.

Rejected because Beamtalk sends are dynamic and the static type is often Dynamic. ADR 0127 rejected "extension methods on a protocol" for the same reason. Concretely:

A library-level registry: Json register: aMapping for: Money

Solve JSON in the JSON library and add nothing to the language. Rejected as the general answer: it is one registry per library, each with its own lookup, reload and ownership behaviour, and x asJson still would not work on the class. It remains a reasonable thing for a single library to do.

Fold cross-file >> within one package

Allow Foo >> sel in another file of the package that defines Foo, and fold it into the class at build time as the same-file fold does. Rejected: "one file is one compilation unit for its class" (docs/beamtalk-language-features.md) is what makes reload replace a class whole, and a cross-file fold would make a class's compiled form depend on which other files the build saw. No package does this today.

Deprecate with a warning for a release, then remove

The usual path for a breaking change, and the previous draft's plan. Rejected by the owner: no package in the survey uses the feature, so a warning period would protect nobody that can be seen, and it would keep both the machinery and its tests alive for another release. The cost is that a private package using it breaks at its next build without warning; the error message carries the migration.

Deprecate in documentation only

Leave the runtime and tell people not to use it. Rejected: the cost is in the dispatch path and the tools, not in user code.

Consequences

Positive

Negative

Neutral

Implementation

Sizes are rough (S, M, L).

Phase 0: inventory (S)

Produce the list that Phases 1 and 2 work from. Known so far:

Exit: the list is complete and each item has a disposition.

Phase 1: make cross-file >> an error, and migrate (M)

There is no deprecation warning. One change does all of this:

Phase 2: delete the machinery (L)

Three steps, in this order, each its own PR. Phases 1 and 2a may be one PR if that is cleaner.

Compiled code from before this change. Every module built by an older compiler calls beamtalk_extensions:has/2 from its generated has_method/1, with no try around it (dispatch_spec.rs:478), and a module with a cross-file extension calls register/5 on load. Loaded into a runtime without the module, such a BEAM fails with undef on ordinary sends. What prevents that is the build stamp: a build is invalidated when BEAMTALK_VERSION changes (crates/beamtalk-cli/src/commands/build_stamp.rs) (reviewer), so a normal build recompiles everything. Step 2c must confirm that dependency BEAMs built ahead of time and BEAMs a workspace has persisted are covered by the stamp. If they are not, 2c keeps a stub beamtalk_extensions for one release (has/2 answers false, lookup/2 answers not_found, register/5 raises a structured error naming this ADR).

2a. Compiler. Delete extension_index.rs, extension_conflicts.rs, ClassHierarchy::register_extensions (class_hierarchy/mod.rs:850) and its class-side "extension replaces signature" rule (BT-5061, BT-5111), the pkg@Target >> qualifier, and the WS3 plumbing: crates/beamtalk-project/src/dependency_extensions.rs, the dependency_extensions_unknown guard (class_hierarchy/mod.rs, receiver_knowledge.rs, consulted.rs), and its carriers in beamtalk-package (dependency_classes.rs, lint_pipeline.rs, manifest.rs), beamtalk-language-service, beamtalk-mcp (server/lint.rs) and the CLI build commands. LSP and language-service code that indexes extension locations goes with it.

2b. Instance-side runtime.

PieceWhere
Extension probes in generated codebeamtalk_extensions:lookup in the actor and value default arms and the beamtalk_extensions:has step of has_method/1 (gen_server/dispatch.rs:769-786, core_erlang/dispatch_spec.rs:355, 478, supervisor_codegen.rs:239)
Interleaved lookupsbeamtalk_dispatch.erl: the extension checks in lookup/5, super/5 and lookup_in_class_chain/5; the {ext, Owner} verdict of inherited_target/2; inherited_value_ext/5. check_extension/2 itself stays until 2c, because class-side code still calls it
The one-hop gap and its warnings (BT-5060, #5718)one_hop_children_missing_extension/2, one_hop_parent_extensions_missing/1 (beamtalk_dispatch.erl:339, 368); warn_one_hop_children/2, warn_one_hop_for_class/1, emit_child_warning/3, emit_parent_warning/3 (beamtalk_extensions.erl:316-410); warn_one_hop_gaps/1 (beamtalk_repl_loader_activate.erl:156); with_extension_warning_scope/2 and its '$extension_scope' rows (beamtalk_class_registry.erl:432); the bt5060_live_* fixtures. The slow routing of one_hop_selectors (value_type_codegen/dispatch.rs:308) can then go straight to the superclass's dispatch/3
Guards against an extension overriding a known selectorThe String-extension gate on the Binary fast path (binary_or_string_module/2, beamtalk_primitive.erl:1005-1010); the per-level extension probe on the equals: / isKindOf: default-chain path (beamtalk_behaviour_intrinsics.erl:373-482, described in beamtalk_equality.erl:120-140); beamtalk_collection_selectors.erl:90-127 (BT-3951); beamtalk_default_method:note_override/2 on registration (inferred: each needs checking that the extension case is its only reason)
Reflection and toolingrespondsTo: and canUnderstand: extension checks (beamtalk_behaviour_intrinsics.erl); the extension-first step of removeSelector: and purge_extensions (beamtalk_class_refactor.erl, beamtalk_class_lifecycle.erl:127-132); SystemNavigation extendersOf: / extensionsBy: and every extension branch in its other queries (Phase 0 list), then regenerate class_hierarchy/generated_builtins.rs; the browse extension provenance (beamtalk_repl_ops_browse_origin.erl); extension xref rows; ChangeLog extension entries (beamtalk_repl_loader_changelog_entries.erl); beamtalk_interface.erl; extension output in beamtalk doc (doc/extractor.rs). These go before the registry is deleted, or sendersOf: and the other queries fail with undef

2c. Class-side runtime, and the registry. 2b and 2c may be one PR. After Phase 1 the class-side path is reachable only through FFI and its tests are gone, so it should not be left in place for long.

PieceWhere
Class-side extension-first orderclass_side_extension/2 (beamtalk_class_dispatch.erl:945) and its callers in handle_class_method_call/6 and walk_class_side; the extension verdict of the owner memo (BT-4800); invoke_class_extension/7 (ADR 0130) (reviewer)
Constructor extensionsThe class-side-extension half of the new / new: check in beamtalk_object_class.erl:1907 and ancestors_have_user_new1 (beamtalk_class_metadata.erl:1668) (BT-4409, BT-4588). The ADR 0084 runtime-fun half stays
Remaining callersbeamtalk_class_dispatch_self.erl; the extension-triggered invalidation of the conformance cache (beamtalk_protocol_registry.erl) and of the class-derived cache; then beamtalk_dispatch:check_extension/2
Shared helperMove safe_xref/1 out of beamtalk_extensions into beamtalk_xref (or a leaf module below both) before deleting the registry; its three callers are ordinary hot-patch and class-removal paths
StartupThe beamtalk_extensions:init() calls in beamtalk_runtime_app.erl:31 and beamtalk_test_boot.erl:99, 264
The extension shadow-flag kindbeamtalk_class_shadow_flags.erl, and the direct-call-key invalidation that an extension registration triggers. runtime_fun and class_vars stay
The registry itselfbeamtalk_extensions.erl, deleted last, with beamtalk_test_extensions.erl

Tests that must still pass after each step:

A benchmark run (docs/development/benchmarks.md) before and after 2b records what the removed probes cost.

Phase 2b and 2c as landed (BT-5141, runtime and stdlib half). 2b and 2c went in one change, as the 2c preamble allowed. Where the plan above differs from the code:

Migration Path

A cross-file extension has no direct replacement, and there is no deprecation period.

You haveDo this
Foo >> sel in another file of the package that defines FooMove the method into Foo's file
String >> shout or another addition to a class you do not ownA method on your own class that takes the value: Shout of: aString
An extension that overrides a method of a class you do not ownSubclass, if the class is not sealed, or wrap
A class-side extension used to patch a class in another packageFix it in that package and redeploy (Open Question 1)
Foo asJson on a foreign FooA using: converter in the holder's JsonMapping (Decision §5)

Known affected code outside this repository: the beamtalk-uat fixture only, which is migrated with Phase 1. There is no warning period: a package the survey could not see gets the compile error on its next build, with the hint above. The change is listed as breaking in CHANGELOG.md and the release notes.

Future direction: retroactive protocol implementations

This section is not part of the decision. It records the design worked out in the first draft so that it is the starting point if the need appears.

Trigger. A concrete package that needs to attach a protocol to a class it does not own, for example a package that must make another package's value class JsonRepresentable. One real case also supplies what the design could not settle on paper: who owns what, and so which ownership rule is right.

Outline. A top-level declaration makes a class answer a protocol's selectors, allowed only where it cannot change what a compiled method does:

F1. Syntax

// app/src/Money+JsonRepresentable.bt
JsonRepresentable implementFor: Money
  asJson => #{"amount" => self cents, "currency" => self currency}

The header is ProtocolName implementFor: ClassName. The indented body holds method definitions, written as in a class body. A class-side method is prefixed class, as in a class or protocol body.

The owner's sketch ended the header with =>. This draft drops it. Protocol define: X and Object subclass: X are the existing declaration headers and neither takes =>; => introduces one method body everywhere else. This is a recommendation, not a decision.

Either name may be package-qualified as ADR 0070 allows: json@JsonRepresentable implementFor: money@Money.

The file convention from ADR 0066 stays, with the protocol as the feature: Money+JsonRepresentable.bt. One file may hold several implementations.

A provided method comes with the protocol. This is the BT-2819 gap closed:

JsonMappable implementFor: Money
  class jsonMapping -> JsonMapping =>
    JsonMapping new
      |> mapField: #cents to: "amount"
      |> mapField: #currency
// Money now answers `asJson`, which JsonMappable provides.

F2. Rule: additive only

An implementation may add selectors. It can never change what a compiled method does.

At compile time:

error: JsonRepresentable implementFor: Money defines `asJson`, but Money already
       defines `asJson` (money/src/money.bt:14).
  = an implementation can add selectors to a class; it cannot replace one.
  hint: delete this method; Money's own `asJson` already answers.

Provided methods. Every provision of the protocol is registered for the class, whatever the class already understands. Miss-only lookup makes that safe: a provision the class already answers with a compiled method never runs. For typing and reflection the compiler computes which provisions are shadowed.

At run time:

The guarantee, stated exactly. With cross-file >> already gone, loading a package cannot change the result of a send that a compiled method answers. It can make a send answer that used to raise does_not_understand, which is the purpose, so code that branches on respondsTo: or catches DNU can observe it. It cannot change which implementation another package's send reaches, because of the clash rule.

This keeps the property the removal buys: no dispatch path, static call or cache has to ask whether something outranks a compiled method.

The cost is real and deliberate: an implementation cannot customise a selector that Object or another ancestor already defines. Printable implementFor: Money with a printString body is an error, because Money inherits printString.

F3. Rule: ownership

An implementation is allowed only if the declaring package owns the protocol or the class.

Definition of "owns". Each class and protocol resolves to exactly one owner, and the check compares that owner with the declaring package:

EntityOwner
A class or protocol in a file compiled under a beamtalk.tomlThat manifest's [package] name
A class or protocol carried in from a dependencyThe dependency's package name (ClassInfo.package, ProtocolInfo.package)
A stdlib class or protocol, including bootstrap builtins whose ClassInfo.package is None (such as Future)stdlib
A class or protocol defined at the REPL, or in a script outside any projectThe workspace's package
Anything whose owner cannot be resolvedUnknown. An unknown owner never matches, so the implementation is refused

The declaring package is the [package] name the file is compiled under, or the workspace's package at the REPL.

This needs one resolver, written once, because None in ClassInfo.package means "REPL classes and bootstrap builtins" (class_info.rs:330-333) while None in ProtocolInfo.package means the package being compiled (protocol_registry.rs:141-145) (read). It also needs every protocol's signatures and owner to reach consumers. Today only protocols with provided methods, and protocols named like a stdlib trait, are carried into other compiles (is_carried_protocol, trait_expansion.rs:567) (read), so a requirements-only protocol such as JsonRepresentable may reach a consumer without its requirement list or owner (reviewer).

So a user package may implement its own protocol for String. It may not implement stdlib's JsonRepresentable for another package's Money.

error: package `app` cannot implement JsonRepresentable (owned by `stdlib`)
       for Money (owned by `money`): it owns neither.
  hint: ask `money` to implement it, or declare a protocol in `app`.

In an acyclic dependency graph, at most one package can satisfy the rule for a given protocol and class from each side, and both sides at once would need the two packages to depend on each other. So for any protocol and class in different packages there is exactly one package that may write the implementation without a circular dependency, plus the degenerate case where one package owns both.

What the rule guarantees, and what it does not. In Rust the orphan rule gives coherence because a method belongs to its trait. Beamtalk selectors are global and conformance is structural, so the rule is much weaker here. The owner should decide with this in view:

As written, then, the ownership rule costs ceremony and protects little. The three coherent positions are listed under "Questions to settle then" below. Choosing between them needs a real case, which is one reason this design is deferred.

F4. Rule: declared conformance

An implementation is a declaration that the class conforms.

F5. Rule: call sites unchanged

x asJson is an ordinary send. respondsTo:, canUnderstand:, perform: and super see an implemented method, after compiled methods. The respondsTo: #asJson hook in beamtalk_json.erl:344-350 needs no change.

>> (Money cents: 250 currency: "EUR") asJson
=> #{"amount" => 250, "currency" => "EUR"}
>> Money conformsTo: #JsonRepresentable
=> true
>> (Money >> #asJson) origin
=> #JsonRepresentable

F6. Class-side requirements

implementFor: supports the protocol's class-side requirements (BT-1611, ADR 0144), written class selector => body. The same rules apply on the class side: additive only, miss-only lookup after the class-method chain. After the implementation the class conforms on both sides, so it is accepted where P class is expected.

A class-side implemented method is compiled as the class-side extension fun was, fun(Args, ClassSelf) -> Result (ADR 0130 §3). It runs where a class method of the target class runs under ADR 0142: in the caller, unless the class or an ancestor declares class variables or the selector is process-bound, in which case it runs in the class process. That is what a class-side extension did (ADR 0142, BT-4307).

Class-side provisions are still post-v1 in ADR 0127 §1; this ADR does not change that.

F7. What an implementation body may do

F8. Hot reload and removal

F9. Questions to settle then

  1. The ownership rule. As stated in F3 it can be sidestepped with a local protocol, and it blocks the plain form of the motivating case. Three coherent positions:
    • (a) Selector-based, with a root-package exemption. A package may not make a foreign class answer a selector that a dependency's protocol declares, unless it owns that protocol or the class. The root package of a build is exempt, because nothing depends on it; an orphan implementation in a dependency is an error. This is the only option that does what the rule was proposed to do. "Root package" means the package being built, not a package with an [application] section; a library can have one.
    • (b) As stated in F3. Simple, and documents intent, with the loophole accepted.
    • (c) A lint. No hard rule; warn on an orphan implementation in a library, as Clojure's guidance does. The clash rule in F2 remains the real protection. This strengthens the case for additive-only >> instead.
  2. Header syntax. With or without a trailing =>; whether there is also a reflective message form for live use (principles 6 and 11); the removal selector.
  3. Run-time clash behaviour. Ambiguous (neither answers, F2) or first-registered-wins with a warning.
  4. Slot and class-variable access from implementation bodies (F7), and whether the class's own package gets more.
  5. REPL strictness. Whether the ownership rule applies at the REPL.
  6. methods and includesSelector:. Whether they list implemented selectors.
  7. Whether this is the right replacement at all. Additive-only >> and pure protocol dispatch (Alternatives) should be re-weighed against the real case.

A first implementation step would be a wire check: register a hand-written fun in a miss-only table through FFI, hook the root DNU path, and run the lookup-order matrix for a value class, an actor, a primitive, a class-side send, a class with its own doesNotUnderstand:args:, respondsTo:, perform: and super. DNU handling is generated per class today (gen_server/dispatch.rs:986-1021) (read), so whether the hook has one choke point is a real question.

Open Questions

  1. Patching a method of a class with no stored source. After removal, a method of a stdlib or dependency class cannot be added or replaced from another package; the route is to fix the owning package and redeploy (Decision §4). Options:

    • (a) Accept the loss. Remove the class-side extension path with the rest. File follow-ups for the two gaps the survey of the patch paths found: MCP save_method and Class compile:source: have no class-side form although install_method/9 supports one, and the workspace stores no source for dependency classes, so they cannot be patched live at all.
    • (b) Keep class-side cross-file >> (compiler and runtime) until the workspace can patch a dependency class live. This keeps the extension shadow flag, the extension-first order and the registry.

    Default taken by the implementation: (a). The reasons: no package uses a class-side extension; a workspace already drops a cross-file >> on load, so the capability exists only through a rebuild, which is what (a) asks for anyway; and (b) keeps most of the class-side cost this ADR exists to remove. Because Phase 1 makes class-side cross-file >> a compile error, choosing (b) means changing Phase 1, so the owner should say so before Phase 1 lands.

Decided, and recorded here:

References