add-from-ion-decoding: design

OpenSpec change | 2026-10-30 | proposed

Context

See proposal.md for the motivation and the value-codecs spec for the rules. @ion has pub(open) trait ToIon and impl ToIon for Json. The Ion to JSON direction (@json.to_json) lives in pkgs/json, which depends on pkgs/ion. MoonBit lets an impl live only in the package of the trait or of the type, so impl FromIon for Json must be in pkgs/ion.

Goals and non-goals

Goals: one decode trait and one decode error type that library users and Moon-Lander can match on; exact, total rules per type; no change to how the readers and writers behave.

Non-goals: derive support; decoding helpers for user structs (such as a required-field reader); coercions between Ion types; tuples of more than three elements.

Decisions

ERR-1. A new suberror, not new IonError cases

pub(open) trait FromIon {
  fn from_ion(Ion) -> Self raise FromIonError
}

pub(all) suberror FromIonError {
  TypeMismatch(path~ : Array[PathSegment], expected~ : IonType, actual~ : IonValueKind)
  OutOfRange(path~ : Array[PathSegment], actual~ : IonValueKind, range~ : ValueRange)
  WrongLength(path~ : Array[PathSegment], actual~ : IonValueKind, expected~ : Int)
  DuplicateField(path~ : Array[PathSegment], name~ : String)
  MissingSymbolText(path~ : Array[PathSegment], token~ : SymbolToken)
  JsonDecode(path~ : Array[PathSegment], message~ : String)
}

pub(all) enum PathSegment { Name(String); Index(Int) }
pub(all) enum ValueRange { Integers(min~ : BigInt, max~ : BigInt); Float32 }

IonError is pub(all) and its cases hold a message string. New cases would break every exhaustive match downstream, and would mix "the input is not valid Ion" with "valid Ion is not the shape I want". A separate type keeps the reader and writer contracts as they are and gives each decode failure a structured payload. Like IonError, it derives Debug and has message(); it also has path() and within(PathSegment).

actual keeps the whole IonValueKind of the value that failed (a shared reference, not a copy). A typed null therefore shows as Null(Int), which tells null.int apart from a value of a different type without an extra case. TypeMismatch also states the expected IonType; in the other cases the range, the length or the case itself is the expectation.

ERR-2. Paths are built while the error returns

A path is an array of segments, outermost first. A container decodes each element, catches its error and raises error.within(segment), which puts the segment in front. The cost falls only on the failure path. A user FromIon impl can call within to add its own field names. message() renders the path as $, .name for a field and [i] for an index, for example $.events[1]: expected int, found string.

RULE-1. Decode accepts only what encode writes

Each type reads only the Ion type that its ToIon writes. A symbol is not a String, a decimal or an int is not a Double, an int is not a Decimal, a clob is not Bytes and an S-expression is not an Array. Ion keeps these types apart on purpose, and an implicit conversion loses precision or meaning without notice. One rule is easy to state and to test. A caller who wants a coercion decodes as Ion and converts. Annotations are ignored, because ToIon writes none and a payload can carry a type annotation that the decoder of the payload does not need.

RULE-2. Numeric limits

Integers decode only when the value is in the target range; otherwise OutOfRange with Integers(min, max). Byte is the range 0 to 255. Float rounds the Ion float to the nearest Float, because a text float such as 0.1e0 has no exact Float; a finite value that rounds to an infinity is OutOfRange with Float32. NaN and the infinities pass through.

NULL-1. Option and typed nulls

None writes the untyped null. Every null, typed or untyped, reads as None: the decoder of T? cannot know the Ion type of T, and "null means absent" is how Ion data is used in practice. Unit reads only the untyped null. Consequence: Some(x) does not round-trip when x itself writes a null (T is Unit, Ion, Json or an Option); it reads back as None.

MAP-1. Duplicate field names are an error

Ion structs may repeat a field name; a Map cannot. The decoder raises DuplicateField instead of keeping the first or the last value, so no data is dropped without notice. A field name with no text raises MissingSymbolText; an Ion 1.0 system symbol ID resolves to its text, as in the JSON conversion. Key order follows the struct.

JSON-1. The Ion to JSON conversion moves to @ion

The conversion code moves from pkgs/json/to_json.mbt to pkgs/ion, unchanged, and backs impl FromIon for Json. @json.to_json stays as a wrapper with the same signature that maps MissingSymbolText to IonError::Unsupported. To keep the stack-safe conversion as fast as before, it does not track a path; after a failure, a second walk with an explicit stack finds the path of the first symbol with no text, in the same document order.

BRG-1. Bridge names and placement

pub fn[T : ToJson] to_ion_via_json(value : T) -> Ion
pub fn[T : FromJson] from_ion_via_json(value : Ion) -> T raise FromIonError

The names mirror to_ion and from_ion and say how the conversion happens, so a bridge impl reads as impl FromIon for Event with from_ion(v) { @ion.from_ion_via_json(v) }. They live in pkgs/ion, next to the traits and both JSON directions (see JSON-1), and pkgs/json re-exports them; there is no cycle. A second reason: derive(FromJson) expands to code that names @json, which inside pkgs/json is the package itself, so derived examples cannot compile in its tests or README. A caller that imports only @ion has everything it needs.

The JSON step follows to_json rules, so it folds duplicate field names onto the last and drops annotations; that is the documented cost of the bridge. Core's derived JSON form leaves out a None field and rejects an explicit null for it, so Ion written by hand for a bridged type leaves the field out. A JsonDecodeError becomes JsonDecode with core's message. Core's JsonPath is opaque and renders as a JSON Pointer, so the bridge walks the pointer through the JSON value: a step into an array is an index, any other step is a field name.

Alternatives: from_json_value and decode_via_json (asymmetric names), and bridges only in pkgs/json (derived examples cannot compile there).

Risks and trade-offs

RiskMitigation
Strict rules reject hand-written Ion such as 1.5 for a Double field.The error names the path and the expected type. Callers can decode as Ion and convert.
Option of a null-writing type does not round-trip.Documented in the spec and the trait docs; property tests exclude it.
Moving the JSON conversion could change its speed.The code moves without change; the path search runs only after a failure.
The message of @json.to_json errors changes.The error case is still Unsupported; noted in the pull request.

Migration plan

Additive. Existing callers of @json.to_json keep working. Moon-Lander can bump its pin to the release that contains this change and match on FromIonError.