ADR 0147: Map-Shape Types for Keyed Dictionaries

Status

Implemented (2026-11-12)

Implementation Tracking

Epic: BT-4726 Issues:

PhaseIssueTitleSizeBlocked by
1BT-4727Parse shape type annotations: AST, parser, unparse, formatterM–
2BT-4728Make type-string handling brace-awareM–
3BT-4729InferredType::Shape: resolution from annotations and aliases, displayMBT-4727, BT-4728
3BT-4730Shape assignability: shape-to-shape, shape-to-Dictionary, gradual ruleMBT-4729
4BT-4731Infer shapes for symbol-keyed map literalsMBT-4730
5BT-4732Shape-aware keyed operations: at: family, at:put:, map patterns, union receiversMBT-4730
gateBT-4733Wire check: buccaneer WebSocketOptions as a shape, end to endSBT-4731, BT-4732
6BT-4734FFI: map Erlang := / => map specs to shapes, gated on a measured warning countMBT-4733
7BT-4735LSP: shape key completion and hoverMBT-4733
8BT-4736Migrate option aliases to shapes: buccaneer, beamtalk-http, stdlib castsMBT-4733
9BT-4737Language docs and end-to-end tests (final phase)MBT-4734, BT-4735, BT-4736

Status: Done

Context

Problem statement

Dictionary(K, V) gives every value the same type. Real Beamtalk code often uses a dictionary as a record instead: each key has its own value type. The checker only sees V, usually Object or Dynamic, so every read loses its type and the code narrows by hand.

The clearest case is option maps. buccaneer declares:

/// - `#maxFrameSize` (Integer, default `8000000`) — ...
/// - `#validateTextFrames` (Boolean, default `true`) — reject non-UTF-8 text frames.
/// - `#compress` (Boolean, default `false`) — ...
/// ...
type WebSocketOptions = Dictionary(Symbol, Object)

The same shape is then written twice more: as a key list (class websocketKeys -> List(Symbol)) and as a runtime validator (class checkWebSocketOptions:). The reader casts each value back (src/pipeline.bt):

ws := config websocket
// Types checked in BuccaneerConfig>>checkWebSocketOptions:.
validateText :: Boolean := ws at: #validateTextFrames ifAbsent: [true]
maxFrameSize :: Integer := ws at: #maxFrameSize ifAbsent: [8000000]

So the shape is stated three times (doc comment, key list, validator), and none of the three is checked at compile time. A caller who writes #{#maxFramSize => 1} finds out at startup. These annotated-local casts are also a large share of the unchecked narrowing casts BT-4719 wants to make visible.

The second case is FFI. Erlang specs describe keyed maps precisely (#{k := T, k2 => T2}), but beamtalk_spec_reader:map_type/1 maps every map type without a '$beamtalk_class' tag to bare Dictionary. ADR 0075 lists "typed maps" as future work. beamtalk-http shows the cost: it calls (Erlang uri_string) parse: url, whose spec names seven keys with their types, and then re-checks each value with isKindOf:.

Current state

A survey of literal-key at: reads in the stdlib's sibling libraries:

RepoSymbol keysString keysString keys come from
buccaneer890–
beamtalk-http110–
catalina160–
exdura345JSON request bodies
symphony3717YAML config, codex JSON-RPC
beamtalk-linear036Linear GraphQL responses
beamtalk-agents056Claude and codex stream-json

The split is clean. Symbol keys are internal option and config maps, plus FFI maps. String keys are decoded external data (JSON, YAML). This ADR covers the first group only; see "String keys" under Alternatives Considered.

Eleven aliases across buccaneer, catalina and beamtalk-http have the form type XOptions = Dictionary(Symbol, Object | Dynamic) with the keys listed in a doc comment.

What already exists in the compiler:

Constraints

Decision

Add shape types: a structural type for a dictionary with known symbol keys, each with its own value type. A shape is written like the map literal it describes, and is usable anywhere a type is: annotations, type aliases, generic arguments, unions.

type WebSocketOptions = #{
  ?#enabled => Boolean,
  ?#maxFrameSize => Integer,
  ?#maxFragmentedMessageSize => Integer,
  ?#validateTextFrames => Boolean,
  ?#compress => Boolean,
  ?#deflateOptions => Dictionary(Symbol, Object),
  ?#maxInflateRatio => Integer,
  ?#primitiveOpsModule => Object,     // reserved, accepted for Bandit parity
  ?#logProtocolErrors => Object       // reserved, accepted for Bandit parity
}

Syntax

ShapeType  := '#{' [ Field { ',' Field } [ ',' '...' ] | '...' ] '}'
Field      := [ '?' ] Key '=>' Type
Key        := SymbolLiteral

Optional is a property of the key, not the value. ?#k => T means the key may be missing. #k => T | Nil means the key is present and may hold nil.

Semantic model

The model is Elixir's set-theoretic map types, the same source ADR 0102 took its operators from. A shape denotes a set of maps:

Subtyping is inclusion between those sets. The rules below are that inclusion spelled out, not a separate design.

Subtyping

Dictionaries are immutable, so shapes are covariant in their value types.

Shape to shape. S is assignable to T when all of these hold:

  1. Every required key of T is required in S, with an assignable value type.
  2. Every optional key of T that S has (required or optional) has an assignable value type. If S lacks it, S must be closed.
  3. Every key of S that T does not name is allowed only if T is open.
  4. If S is open, T is open.

Shape to Dictionary(K, V). A closed shape is assignable when every key type is assignable to K and every value type to V. An open shape's unnamed entries are Object-keyed and Object-valued, so it is assignable only when K and V accept Object (or are Dynamic). Bare Dictionary accepts any shape.

In particular a closed shape is assignable to Dictionary(Symbol, V) whenever every field type is assignable to V, so Dictionary(Symbol, Object) accepts every closed shape, and Dictionary(Symbol, Integer) accepts one whose fields are all Integer. Maps are immutable values, so a helper that takes a Dictionary cannot break the shape. A generic validator over symbol-keyed maps (for example one taking d :: Dictionary(Symbol, Object) and a key) should therefore be annotated Dictionary(Symbol, Object), not with a particular shape alias. A field type that is not assignable to V, or a non-Symbol key type, is still rejected, and the shape-specific checks (missing key, did-you-mean on a misspelt key) are unchanged. (BT-4733)

Dictionary to shape. Follows the existing gradual rule for generics (type_args_match):

Map literals infer shapes

A map literal whose keys are all symbol literals infers a closed shape, with nested literals inferring nested shapes:

opts := #{#body => "{}", #timeout => 5000}
// #{#body => String, #timeout => Integer}

Any other literal (a computed or non-symbol key) infers Dictionary(K, V) as today. Checking a literal against a declared shape is then ordinary shape-to-shape assignability, including through an unannotated local, with diagnostics that name the offending key.

This is needed, not optional. Without it opts := #{...} followed by passing opts to a shape-typed parameter would warn, because the local would be a fully typed Dictionary.

The Dictionary(K, V) view of an inferred shape (see below) is exactly the type infer_map_literal gives today, so sends that are not shape-aware see no change.

Shapes in the type algebra (ADR 0102)

The fieldwise intersection rule follows from the model and is recorded here for the narrowing work (BT-4709) to implement, since that is its only user. A key in both sides takes the intersection of the value types and is required if either side requires it. A key in one side only is kept if the other side is open; if the other side is closed it is dropped when optional and makes the result Never when required. A key whose value types intersect to Never is dropped if optional on both sides and makes the result Never otherwise. The result is open only if both sides are. includesKey: #k in the true branch is then S & #{#k => Object, ...}.

Diagnostic severity

Shape diagnostics follow ADR 0100: default severity is Warning, never a build-stopping error unless a project opts in.

SituationDefault
at: / at:ifPresent: / map pattern on a key a closed shape does not nameWarning (the read can only fail or never match)
at:ifAbsent: on a key a closed shape does not nameWarning (the block always runs)
Literal checked against a shape: missing required key, unknown key in a closed shape, wrong value typeWarning
Optional key read with at:, or unnamed key in an open shapesilent

A misspelt key aimed at a closed shape gets a "did you mean" whether the target key is optional (reported as an unexpected key) or required (reported as missing required key with a did you misspell it as note, BT-4737).

Shape-aware operations

Only these operations use the per-key types. The key argument must have a singleton symbol type (#k). A literal #k has one; so does a local bound to one. A key typed as a union of singletons answers the union of the per-key results.

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

at:put: is here because real code builds option maps with it (options at: #handler put: handler in Buccaneer start:handler:), and a Dictionary result would not be accepted where the shape is expected.

Union receivers. A keyed read on a union (S1 | S2, S | Nil, S | Tuple) answers the union of each member's result, with non-shape members typed as they are today. The "key not in shape" diagnostic fires only when every member is a closed shape lacking the key.

isKindOf: Dictionary narrowing keeps the shape members of a union: a shape is a Dictionary.

Every other message treats the shape as Dictionary(K, V), where K is the join of the key types and V the join of the value types (Object for both if the shape is open). That includes any keyed message with a key that is not a singleton symbol, keys, do:, collect:, and, in this ADR, removeKey: and merge:, which answer a Dictionary(K, V).

Runtime

None, and no change to generated code. Shapes are erased like every other annotation, and a shape in a signature still emits map() in the Erlang -spec, as Dictionary does today. They describe maps the program builds itself (options, config) and maps a trusted FFI spec describes. They are not a way to validate external data: that should still be parsed into Value classes at the boundary, as beamtalk-linear's Issue fromNode: does.

FFI mapping

The spec reader maps Erlang map types to shapes:

Erlang fieldBeamtalk
k := T (map_field_exact, atom key)#k => T
k => T (map_field_assoc, atom key)?#k => T
a non-singleton key field alongside atom keys (atom() => term())trailing ...
a field keyed by true, false or niltrailing ... (those atoms are not symbols in Beamtalk)
no singleton keys at all (#{atom() => integer()}, map())Dictionary, as today
'$beamtalk_class' := Cthe class C, as today (checked first)

Erlang type syntax has no binary-literal keys, so symbol keys cover every keyed map a spec can describe. Turning a typed domain field (atom() => integer()) into ... loses its value type; that is accepted.

Value types are whatever the reader already produces for them, which is often loose (unicode:chardata() is Dynamic | String | Binary). A shape does not make those tighter; it adds the key set and keeps each key's type separate.

This applies to parameters as well as results: an Erlang function that takes a keyed map now expects a shape. The gradual rule and literal inference above keep existing callers quiet unless they pass a fully typed Dictionary.

FFI specs are trusted exactly as ADR 0075 already trusts them. Emitting shapes back into Erlang -specs is deferred (see below).

Worked examples

Config (buccaneer). With the alias above:

ws := config websocket
validateText := ws at: #validateTextFrames ifAbsent: [true]    // Boolean
maxFrameSize := ws at: #maxFrameSize ifAbsent: [8000000]       // Integer

The two casts and the comment that excuses them go. With ConfigOptions also written as a shape (?#websocket => WebSocketOptions, ...), the call site is checked too:

Buccaneer start: #{#handler => h, #websocket => #{#maxFramSize => 1}}
// warning: no key #maxFramSize in WebSocketOptions (did you mean #maxFrameSize?)

The runtime validator stays for value-range checks (positive integers) and for callers that build the map dynamically.

Options (beamtalk-http).

type RequestOptions = #{
  ?#headers => List(List(String)),
  ?#body => String,
  ?#timeout => Integer,
  ?#maxBodyBytes => Integer | #unlimited
}

HTTPClient request: #patch url: u options: #{#body => "{}", #timeout => "5s"}
// warning: #timeout expects Integer, got String

FFI (uri_string:parse/1). The OTP type is:

-type uri_map() ::
  #{fragment => unicode:chardata(), host => unicode:chardata(),
    path => unicode:chardata(), port => non_neg_integer() | undefined,
    query => unicode:chardata(), scheme => unicode:chardata(),
    userinfo => unicode:chardata()}.

parse/1 returns uri_map() | error(). Today that reads as Dictionary | Tuple(Symbol, Symbol, Dynamic); with this ADR it is a closed shape with seven optional keys, or the tuple. In HTTPClient urlParts::

raw := (Erlang uri_string) parse: url
(raw isKindOf: Dictionary) ifFalse: [^self httpError: "Invalid URL"]
port := raw at: #port ifAbsent: [80]       // Integer | Symbol, was Dynamic
scheme := raw at: #shceme ifAbsent: [nil]  // warning: no key #shceme

The gain is the key set and the port type. The text fields stay Dynamic | String | Binary because that is what unicode:chardata() maps to, so the textOf: conversions in that method stay.

REPL

type Point = #{#x => Integer, #y => Integer}
// => "Point"
p :: Point := #{#x => 1, #y => 2}
// => #{#x => 1, #y => 2}
p at: #x
// => 1
p at: #z
// warning: no key #z in Point
// => ERROR: ... key not found (raised at run time, as today)
q :: Point := #{#x => 1}
// warning: missing required key #y for Point

:help Point shows the expanded shape, as it does for any alias (ADR 0108). Diagnostic wording is illustrative and is settled in implementation.

Single sources of truth

Prior Art

LanguageExampleNotes
Erlang typespecs#{name := binary(), age => integer()}:= required, => optional. Closed unless a general key field is present. Checked by Dialyzer and eqWAlizer.
Elixir (set-theoretic, 1.17+)%{name: binary(), age: if_set(integer())}, %{..., name: binary()}Closed by default, leading ... opens. Optional is if_set on the value.
Hackshape('a' => int, ?'b' => string, ...)Closed by default, ... opens, ? prefix marks optional.
Typed Clojure(HMap :mandatory {:a Num} :optional {:b Str} :complete? true)Mandatory, optional and absent keys; partial by default.
TypeScript{a: number; b?: string}Open by width subtyping, but fresh literals get excess-property checks.
Pythonclass M(TypedDict, total=False), NotRequired[int], closed=True (PEP 728)Started open; PEP 728 added closed because open could not type **kwargs or catch typos.
Gleam–No shapes. Dict(k, v) is homogeneous; records are custom types.
Pharo / Squeak–No static shapes. Idiom is a real object, or a Dictionary checked at run time.

Adopted. Elixir's semantic model: shapes are sets of maps, optional is "value or absent", closed by default with ... to open, and shapes take part in union and intersection. This keeps shapes consistent with ADR 0102, which adopted the same model for unions and singletons. Hack's surface for the spelling: literal-like syntax and a ? prefix. TypeScript's literal-site checking. Erlang is the FFI wire format only: its := / => fields translate one-to-one into required and optional keys.

Rejected. Erlang's := / => spelling: in a Beamtalk literal => means "this key is present", so using => for optional would invert it. Elixir's spelling of optional as if_set(T) on the value: the meaning is adopted, but written on the key it reads better beside T | Nil. Open-by-default (TypeScript, early TypedDict): it gives up the typo check that motivates this ADR, and Python's history shows closed gets added later anyway.

User Impact

Steelman Analysis

Rejected: parse into Value classes, add no type

Why not: it does nothing for FFI map specs, and it makes every option literal (options: #{#timeout => 5000}) into a constructor call or leaves it unchecked. The ADR keeps this as the recommended treatment for external data.

Rejected: inference only, no annotation syntax

Why not: the shape is lost at every method boundary. The buccaneer casts sit across a boundary (config websocket), so they would all stay.

Rejected: open by default

Why not: the typo check is the main benefit for option maps. Pass-through maps write ..., which also documents that they are pass-through.

Tension points

Alternatives Considered

Do nothing: keep Dictionary and the annotated casts

BT-4719 is already making unchecked narrowing casts visible, and the runtime validators already catch bad options at startup. This costs nothing in the checker. Rejected because it leaves each option alias stated three times (doc comment, key list, validator), gives no call-site feedback on misspelt keys, and leaves FFI maps as bare Dictionary with no way to do better.

Boolean? for optional keys

#k => Boolean? reads as "nullable Boolean" to anyone from Kotlin, Swift or TypeScript, which is a different thing from a missing key.

String keys (JSON and YAML objects)

#{"id" => String, ...} would cover the 114 string-key reads in exdura, symphony, beamtalk-linear and beamtalk-agents, and map patterns already accept string keys. Left out: that data is external and the types are erased, so a shape over it is an unchecked claim that looks like a guarantee. Those libraries mostly want tag-field narrowing (msg at: "type") and validation, neither of which a shape provides. The right tool today is a Value class built at the boundary. Revisit together with string singleton types.

A named shape declaration (nominal)

shape WebSocketOptions ... as its own declaration kind. Rejected: type aliases (ADR 0108) already name structural types, and FFI shapes are anonymous.

Shapes only where declared, no literal inference

The first draft kept infer_map_literal unchanged and checked a literal against a shape only when it sat directly in a typed position. Rejected after review: opts := #{...} followed by a call, and options at: #handler put: h, are both common in the libraries being migrated and would warn.

Per-key types for every update now

Typing removeKey: and merge: per key in this ADR. Deferred: each adds checker surface, and the surveyed code does not need them. at:put: is in because it does.

Emit shapes into Erlang -specs

#{k := T, k2 => T2} instead of map(). Deferred: it changes generated attributes, and Dialyzer would then check closed map contracts against callers the Beamtalk checker accepted through Dynamic. It needs its own measurement of Dialyzer fallout.

Consequences

Positive

Negative

Neutral

Implementation

PhaseWorkComponentsSize
1TypeAnnotation::Shape: parser (including the ,? split), AST, unparse, formattersource_analysis, ast, unparseM
2Brace-aware type strings: one shared routine for splitting and parsing the string form; fix the #-prefix singleton checks so #{ is not a singletonstring_utils.rs, type_checker/validation.rsM
3InferredType::Shape: resolution from annotations and aliases, display with truncation, shape-to-shape and shape-to-Dictionary assignability, the gradual rule, Dictionary view for all other sendstype_checkerL
4Map literals infer shapes; key-naming diagnostics for shape mismatchestype_checker/inference/literals.rs, validation.rsM
5Keyed operations: at:, at:ifAbsent:, at:ifPresent: (and ifPresent:ifAbsent:), at:put:, map-pattern bindings, union receivers, isKindOf: narrowingtype_checker/inference, narrowingM
6FFI: spec reader maps := / => fields to shapes; shared fixturebeamtalk_spec_reader.erl, native_types.rsM
7LSP key completion and hover; language-features and syntax-rationale docs; surface paritybeamtalk-language-service, docsM
8Prove it: migrate buccaneer config aliases, beamtalk-http RequestOptions / ClientOptions, stdlib system_navigation.bt castssibling repos, stdlibM
9End-to-end tests (BUnit plus one btscript)stdlib/test, tests/repl-protocolS

Phase 3 depends on 1 and 2. Phases 4 and 5 depend on 3. Phase 6 depends on 3 and the gates below.

Wire check (gate before phase 6). Phases 1 to 5 must carry one real alias end to end: buccaneer's WebSocketOptions as a shape, the casts in pipeline.bt removed, a misspelt key at a Buccaneer start: call site reported, and no new warnings elsewhere in buccaneer beyond the one cast at the config validator. If that is noisy or awkward, revisit the design before building FFI mapping and tooling on it.

FFI gate (within phase 6). Before the reader change is switched on, count the new warnings it produces across the stdlib and the sibling libraries. If most are noise from loose value types or domain keys, narrow the mapping (for example, results only) before shipping it.

None of this touches state-threading lowering, so ci:corpus is not needed.

Deferred (each needs its own justification)

Migration Path

Two things change for existing code without any edit:

To migrate an option alias:

  1. Replace the Dictionary(Symbol, Object) alias with a shape taken from its doc comment and its key list. Include every key the validator accepts, reserved ones too.
  2. Where a validator builds the section from an untyped map, assert the shape once there with an annotated local.
  3. Delete the annotated-local casts at the readers.
  4. Keep the runtime validator for value-range checks and dynamic callers.

Field defaults such as field: websocket :: WebSocketOptions = Dictionary new keep working under the gradual rule.

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

Evidence from the downstream adoption epic (BT-5221; full report in docs/research/feature-adoption-2026.md). Shapes are used in three packages. beamtalk-buccaneer and beamtalk-http are the motivating code and predate the epic. beamtalk-oauth tried one on a real response during the epic (BT-5225): type TokenResponse describes the native shim's 7-key token map, with String | Nil and Integer | Nil values, and is the parameter type of OAuthFlows class tokenSetFrom:obtainedAt:. It was kept. A literal with a missing or mistyped key at a call site is rejected (key #access_token expects String | UndefinedObject, got Integer).

The limit: the real response comes from FFI as Dynamic, so the check covers literals at call sites, not the shim's output. The Erlang side is still guarded only by token_to_map/1's contract. beamtalk-catalina decodes no dictionaries and had no site.

Map patterns do not yet have the optional-key form that shapes have (?#k => T). Every key a pattern lists must be present, so linear, agents and oauth keep at:ifAbsent: lookups for optional keys (BT-5344, needs-spec).

Verdict: established.

References