ADR 0155: Optional Keys in Map Patterns

Status

Accepted (2026-11-27)

Accepted as recommended. That includes strict "optional means absent, not nil": a present nil fails ?k => x :: T.

Context

The problem

A map pattern #{#k => v} matches a dictionary that holds every listed key. It ignores extra keys, but a missing key means the pattern does not match: a match: arm falls through, and a destructuring assignment raises #key_error.

Real API data rarely has only required keys. The downstream adoption of the pattern features (epic BT-5221) found the same gap in three packages:

So the code keeps at:ifAbsent: where one pattern would say what the data looks like. BT-5344 asks for map patterns with optional keys.

What exists today

Constraints

Decision

1. Syntax: ? before the key, = literal after the value

A map-pattern key may be marked optional with a leading ?, the same marker ADR 0147 uses for an optional key in a shape type. An optional key may be followed by = default, the same marker as a state:/field: default.

MapPatternPair := [ '?' ] Key '=>' Value [ '=' Default ]     // '= Default' only after '?'
Key            := SymbolLiteral | StringLiteral
Default        := Number | '-' Number | String | Symbol | Character
                | 'nil' | 'true' | 'false' | '#()' | '#{}'

In the REPL:

> #{?#port => port = 80, #host => host} := #{#host => "example.com"}
=> #{#host => "example.com"}
> port
=> 80
> #{?#port => p2} := #{#host => "example.com"}
=> #{#host => "example.com"}
> p2
=> nil
// absent -> nil
#{#id => id, ?#priority => priority} := node

// absent -> the default
#{?"command" => command = "claude", ?"readTimeoutMs" => timeout = 5000} := config

// in a match: arm, with a nested type test
node match: [
  #{"id" => id, ?"priority" => p :: Integer} -> {id, p};
  _ -> nil
]

Rules:

2. Types

An optional binding has the type a required binding would have at that key, joined with Nil when there is no default, or with the default's type D when there is one. ADR 0147 gives at: #k ifAbsent: [b] the same rule: T | B. Today a map-pattern binding is typed only when the scrutinee is a shape (symbol keys, BT-5336). Otherwise it stays untyped (Dynamic), and optional keys do not change that. String keys, which every downstream example uses, therefore type through the x :: T columns only.

Scrutinee?#k => v?#k => v = d?#k => v :: T?#k => v :: T = d
shape, #k => S (required)SSS & TS & T
shape, ?#k => S (optional)S | NilS | D(S & T) | Nil(S & T) | D
shape, #k not named, closedNil + warningD + warningNil + warningD + warning
shape, #k not named, openObject | NilObject | DT | NilT
not a shape (Dictionary(K, V), Dynamic, string keys)DynamicDynamicT | NilT

The :: T columns describe a match: arm, where x :: T is a test. In a destructure it is the declared type of the local (see §3).

D is the default's type. S & T is the intersection BT-5336 already computes for a nested type pattern. An unknown, Object or disjoint position gives the bare T. Two further rules:

Narrowing with a nested x :: T (BT-5294, BT-5328, BT-5332) follows from "optional means absent":

Data?#k => n :: Integer in a match: armin a := destructure
key absentmatches, n = nilbinds n = nil
key absent, = 0matches, n = 0binds n = 0
#k => 5matches, n = 5binds n = 5
#k => "x"no match, next armbinds n = "x" (annotation is trusted, BT-5284)
#k => nilno match (nil is not an Integer)binds n = nil

In a match: arm the type test runs only when the key is present. A present value of the wrong class falls through to the next arm. The test runs in source order with the other nested type tests, after the shape match and before the when: guard. The guard sees every binding. Because of the untagged-map check, a pattern whose keys are all optional matches any Dictionary and nothing else. Exhaustiveness is unchanged: a map pattern never makes a match: exhaustive over a non-map type.

JSON null. A present nil fails ?#k => x :: T, because nil is not a T and a type pattern names one class (x :: String | Nil is not a type pattern). An API that sends explicit nulls is read with ?#k => x, without the test, or the arm matches nil first. Union type patterns would cover this case. They are a separate feature, and this ADR keeps "optional means absent" rather than special-casing nil.

3. Destructuring

Optional keys work the same in #{...} := m as in a match: arm, except that x :: T stays a trusted annotation (BT-5284).

The parser sends a destructure through the pattern grammar when it sees a ?, ,? or = inside the leading #{. The test is the same lookahead leading_collection_is_typed_destructure already uses for ::. With = in the lookahead, #{#id => id = 0} := m reaches the pattern parser and gets the specific "only an optional key can have a default" error, not the generic "'=' is not an operator".

4. Codegen

Required pairs stay in the native map pattern. In a destructure, each optional pair becomes one maps:get/3 with the constant default ('nil' when there is none). In a match: arm, an optional pair with a nested type test becomes one maps:find/2, so the test runs only on a present value and the key is looked up once. No new runtime function is needed.

An arm that has an optional pair always leaves the native single-case fast path. Its bindings come from lets after the clause matches, so a when: guard in clause position could not see them. Such an arm goes through generate_nested_type_arm, the path nested type tests already take, with the guard run last. The predicate that selects that path (pattern_has_nested_type) also checks for an optional pair.

Destructure. #{?"request" => request = #{}, ?"request_id" => requestId} := msg

let _Map@1 = _msg@0 in
let Request@ = call 'maps':'get'(<"request">, _Map@1, ~{}~) in
let RequestId@ = call 'maps':'get'(<"request_id">, _Map@1, 'nil') in
...

Compare a required key today: let Id@ = call 'erlang':'map_get'(<"id">, _Map@17) in .... (<"k"> stands for the tagged string key {'beamtalk_string', #{...}#}, which map_pattern_key_doc already emits. A symbol key is a plain atom.)

match: arm with a nested type test. #{"id" => id, ?"priority" => p :: Integer} -> {id, p}; _ -> nil

case _Match@7 of
  <~{ <"id"> := Id@ }~> when 'true' ->
    case <UNTAGGED-MAP TEST on _Match@7> of           % wrap_untagged_map_test
      <'true'> when 'true' ->
        let <_OptOk@20, P@> =
          case call 'maps':'find'(<"priority">, _Match@7) of
            <{'ok', _V@21}> when 'true' ->
              <call 'erlang':'is_integer'(_V@21), _V@21>     % the existing type test, as a boolean
            <'error'> when 'true' -> <'true', 'nil'>         % or the default
          end in
        case _OptOk@20 of
          <'true'>  when 'true' -> {Id@, P@}
          <'false'> when 'true' -> apply '_Fallthrough@14'/0 ()
        end
      <'false'> when 'true' -> apply '_Fallthrough@14'/0 ()
    end
  <_NoMatch@8> when 'true' -> apply '_Fallthrough@14'/0 ()
end

The type test in the ok branch is the test that dispatch_type_pattern_strategy already builds for a hoisted type pattern. It is built with 'true' as the success continuation and 'false' as the failure, so every class strategy works: BIF guards, the String tag, the class tag, and isKindOf: for classes with subclasses. The arm body appears once. Without a type test the pair is let P@ = call 'maps':'get'(<"priority">, _Match@7, 'nil').

Cost compared with at:ifAbsent:. Today node at: "priority" ifAbsent: [nil] compiles to an is_map test, a maps:get('$beamtalk_class', …) tag lookup, an is_map_key('__class_mod__', …) test, a closure allocation for the block, and a remote call to bt@stdlib@dictionary:dispatch/3. That call dispatches at:ifAbsent: and applies the closure when the key is missing. The pattern lowering is one maps:get/3 BIF per key, plus one is_map_key per key with a type test, which uses one maps:find/2 instead. The untagged-map check runs once per pattern. The pattern allocates nothing and makes no remote call. at:ifAbsent: repeats its class-tag check for every key.

The state-threading machinery is not involved. Defaults are constants and patterns contain no sends, so no ThreadedIr node changes. The implementation PR still carries ci:corpus, because it touches match: arm lowering.

5. Formatter and LSP

Examples from the downstream packages

beamtalk-linear, IssueRef fromNode: (src/issue_ref.bt). Today:

class fromNode: node :: Dictionary -> IssueRef =>
  self
    new: #{
      #id => (node at: "id" ifAbsent: [nil]),
      #identifier => (node at: "identifier" ifAbsent: [nil]),
      #state => ((node at: "state" ifAbsent: [
        #{}
      ]) at: "name" ifAbsent: [nil])
    }

With optional keys:

class fromNode: node :: Dictionary -> IssueRef =>
  #{?"id" => id, ?"identifier" => identifier, ?"state" => stateNode = #{}} := node
  #{?"name" => state} := stateNode
  self new: #{#id => id, #identifier => identifier, #state => state}

A state that is present but null still raises at the second destructure, just as nil at: "name" ifAbsent: raises today.

beamtalk-linear, Issue fromNode: (src/issue.bt): twelve at:ifAbsent: lookups become one pattern that lists the node's keys:

class fromNode: node :: Dictionary -> Issue =>
  #{
    ?"id" => id,
    ?"identifier" => identifier,
    ?"title" => title,
    ?"description" => description,
    ?"priority" => rawPriority,
    ?"state" => stateNode = #{},
    ?"branchName" => branchName,
    ?"url" => url,
    ?"labels" => labelsObj,
    ?"inverseRelations" => relationsObj,
    ?"createdAt" => createdAt,
    ?"updatedAt" => updatedAt
  } := node
  #{?"name" => state} := stateNode
  priority := rawPriority match: [n :: Integer -> n; _ -> nil]
  self
    new: #{
      #id => id,
      #identifier => identifier,
      #title => title,
      #description => description,
      #priority => priority,
      #state => state,
      #branchName => branchName,
      #url => url,
      #labels => (self labelsFromNode: labelsObj),
      #blockedBy => (self blockersFromNode: relationsObj),
      #createdAt => createdAt,
      #updatedAt => updatedAt
    }

priority keeps its match:. In a destructure ?"priority" => p :: Integer is an unchecked annotation, and the original code drops a non-integer priority. A match: arm would test it, but the method has one shape, so a second statement is clearer than a one-arm match.

beamtalk-agents, ClaudeBackend start:config:onEvent: (src/claude_backend.bt). The defaults are the reason the adoption could not use a pattern. Now they sit next to their keys:

class start: workspacePath :: String config: config :: Dictionary onEvent: callback :: Block(Dictionary, Object) | Nil -> ClaudeBackend =>
  #{
    ?"command" => command = "claude",
    ?"permissionMode" => permissionMode = "acceptEdits",
    ?"allowedTools" => allowedTools = #(),
    ?"disallowedTools" => disallowedTools = #(),
    ?"readTimeoutMs" => readTimeoutMs = 5000,
    ?"resumeSessionId" => resumeSessionId
  } := config
  self
    spawnWith: #{
      #workspacePath => workspacePath,
      #command => command,
      #permissionMode => permissionMode,
      #allowedTools => allowedTools,
      #disallowedTools => disallowedTools,
      #readTimeoutMs => readTimeoutMs,
      #onEvent => callback,
      #resumeSessionId => resumeSessionId
    }

beamtalk-agents, handleControl: and usageCounters::

handleControl: msg :: Dictionary -> Result(Dictionary, AgentError) | Nil =>
  #{?"request" => request = #{}, ?"request_id" => requestId} := msg
  #{?"subtype" => subtype} := request
  // ... unchanged

class usageCounters: usage :: Dictionary -> Dictionary =>
  #{?"input_tokens" => input = 0, ?"output_tokens" => output = 0, ?"total_tokens" => total} := usage
  #{"input" => input, "output" => output, "total" => (total ifNil: [input + output])}

total_tokens has a computed default, input + output. Defaults are constants, so it binds nil and ifNil: computes the sum. That differs from at:ifAbsent: only when the key is present and holds nil. Then the sum is used instead of nil, which is the better answer for a counter.

beamtalk-oauth, the authorization callback (src/oauth_flows.bt). Six lookups are spread over forty lines of one method. They become one statement at the top that says which parameters a callback may carry:

#{
  ?"state" => state = "",
  ?"code" => code = "",
  ?"error" => providerError,
  ?"error_description" => errorDescription = "",
  ?"iss" => iss
} := parsed

(parsed includesKey: "error") not becomes providerError isNil. Query parameters are never nil, so the two are the same.

beamtalk-oauth, token-info bodies (src/token_revocation.bt). A match: arm whose keys are all optional matches any Dictionary, so it replaces the isKindOf: Dictionary check as well as the lookup:

class isInactive: status :: Integer body: body :: Object -> Boolean =>
  status =:= 401 ifTrue: [^true]
  status =:= 400 ifFalse: [^false]
  body match: [
    #{?"error" => code} -> code isNil or: [code =:= "invalid_token"];
    _ -> false
  ]

class isForClient: clientId :: String body: body :: Dictionary -> Boolean =>
  #{?"azp" => azp, ?"aud" => aud, ?"application" => app} := body
  azp notNil ifTrue: [^azp =:= clientId]
  // ... the aud / application checks, unchanged

beamtalk-oauth, ID-token claims. aud := claims at: "aud" ifAbsent: [nil] (twice in oauth_flows.bt) becomes #{?"aud" => aud} := claims. The TokenResponse shape in tokenSetFrom:obtainedAt: already has every key, because the shim fills missing parts with nil. That site stays as it is.

Error examples

#{?#type => "blocks"} := r
// error: an optional key must bind a variable or a type pattern, not a literal
//   hint: match the key as required (#type => "blocks"), or bind it and compare

#{?"timeout" => t = defaults timeout} := config
// error: the default of an optional key must be a literal
//   hint: bind the key without a default and use `t ifNil: [defaults timeout]`

{#ok, #{?#k => v}} := pair
// error: optional keys are supported only in a top-level map pattern

#{#id => id = 0} := node
// error: only an optional key (`?#id`) can have a default

#{?#n => n :: Integer = "none"} := m
// warning: default "none" is not an Integer

opts :: #{#a => Integer} := #{#a => 1}
#{?#b => b} := opts
// warning: no key #b in #{#a => Integer}; it is always absent

Prior Art

User Impact

Steelman Analysis

"b"? => b (postfix marker on the key)

"b" => b | 0 (default after |)

"b" => (b default: 0) or "b" => b ifAbsent: 0

Default only, no ? ("b" => b = 0, absent → default, else required)

Computed defaults (?"total" => t = input + output)

Absent required key binds nil in destructuring (no ? needed there)

Tension

Newcomers would trade ? for less typing, as JS does with plain defaults. BEAM veterans and operators want absence to be explicit, so it is visible in the code and the generated Core. The decision keeps it explicit with a one-character marker.

Alternatives Considered

Status quo: keep at:ifAbsent:

It needs no change, and at:ifAbsent: already allows computed defaults. It was rejected because the evidence is three packages in which adopters wanted a pattern and could not use one. A column of lookups hides which keys a record has and costs a closure and a dispatch per key.

A library helper instead of syntax

For example node valuesAt: #("id", "title") ifAbsent: nil, answering a list. It needs no grammar change. It was rejected because positional results lose the key-to-name pairing, defaults would be per call rather than per key, and nothing reaches the type checker or a match: arm.

One marker for the whole pattern (#?{ ... }, every key optional)

Most evidence patterns are entirely optional (Linear 12 of 12 keys, the oauth callback 5 of 5, the agents config 6 of 6). It was rejected because claims, token-info bodies and shapes mix required and optional keys, so a per-key marker is needed anyway. A whole-pattern form could be added later as sugar.

See the Steelman Analysis above for the syntax alternatives (postfix ?, | default, keyword-style default, default-only) and the semantic ones (computed defaults, implicit nil in destructuring). Two lowerings were also considered:

Consequences

Positive

Negative

Neutral

Implementation

One PR (size M), labelled ci:corpus:

  1. AST + parser (ast/pattern.rs, parser/patterns.rs, parser/mod.rs): optional / default on MapPatternPair; the ? and ,? / =- splitting; default validation; the destructure lookahead trigger on ? and =; the top-level-only and mixed-duplicate errors; and the _ :: T map-value parse fix.
  2. Semantic analysis / type checker (type_checker/shape_keyed.rs, inference/flow.rs, pattern_bindings.rs): the binding types in §2, the default-vs-type-test warning, and the always-absent warning.
  3. Codegen (patterns/match_lowering.rs, type_tests.rs, destructure.rs): optional pairs left out of the native pattern; arms with optional pairs routed through generate_nested_type_arm; the untagged-map check; maps:get/3, and maps:find/2 with a boolean type test.
  4. fmt / unparse (unparse/expressions.rs) and LSP hover/semantic tokens.
  5. Tests: key present; key absent; key absent with a default; present but the wrong type under a nested x :: T (no match in match:); destructuring (an optional key never raises, a required key still raises #key_error); parser errors; fmt round-trip. BUnit in stdlib/test/, plus parser, codegen-snapshot and type-checker unit tests.
  6. Docs: docs/beamtalk-language-features.md § Pattern Matching (the Dict/Map row, a subsection, and the "Patterns in Real Code" note that map patterns require every key).

Downstream (after the PR merges and edge is republished): rewrite at least one site per package in beamtalk-linear, beamtalk-agents and beamtalk-oauth, one PR per repo.

Migration Path

None. The change is additive. Every existing map pattern means what it meant before, and ? and = were not valid in a map pattern until now.

References