soma.cell

Records and JSON: serialize a record to a JSON string and parse it back

Demonstrates to_json/from_json round-tripping — the record's _type tag is part of its data, so is_a still recognizes it after a full round-trip.

A Soma program from the records part of the verified corpus: 47 lines, cells JsonRecords, JsonRecordsTest. It passes soma check with soma 3.2.4.

How it is built

The cell JsonRecords declares 5 signals in its face: make() -> Map, as_json() -> String, reparse() -> Map, tag_survives() -> Bool and field_after_parse() -> String. Handlers: make (line 14), as_json (line 18), reparse (line 22), tag_survives (line 28) and field_after_parse (line 32).

The file also holds 1 test cell (JsonRecordsTest) with 6 assertions, run by soma test.

Generated from soma describe on this file.

The source

json_roundtrip.cell

// Records and JSON: serialize a record to a JSON string and parse it back.
// Demonstrates to_json/from_json round-tripping — the record's _type tag is
// part of its data, so is_a still recognizes it after a full round-trip.

cell JsonRecords {
    face {
        signal make() -> Map
        signal as_json() -> String
        signal reparse() -> Map
        signal tag_survives() -> Bool
        signal field_after_parse() -> String
    }

    on make() {
        return Profile { user: "ada", level: 7, prefs: list("dark", "compact") }
    }

    on as_json() {
        return to_json(make())
    }

    on reparse() {
        return from_json(as_json())
    }

    // Record literals carry _type; it serializes and parses back, so the
    // reparsed value is still recognized as a Profile.
    on tag_survives() {
        return is_a(reparse(), "Profile")
    }

    on field_after_parse() {
        return reparse().user
    }
}

cell test JsonRecordsTest {
    rules {
        assert make().level == 7
        assert is_a(make(), "Profile") == true
        assert contains(as_json(), "ada") == true
        assert tag_survives() == true
        assert field_after_parse() == "ada"
        assert reparse().prefs[0] == "dark"
    }
}

What the toolchain says

Run on a fresh copy of the program at build time; the outputs are pasted unedited.

$ soma check json_roundtrip.cell
✓ All checks passed.
$ soma test json_roundtrip.cell
test JsonRecordsTest ...
  ✓ assert make().level == 7
  ✓ assert is_a(make(), "Profile") == true
  ✓ assert contains(as_json(), "ada") == true
  ✓ assert tag_survives() == true
  ✓ assert field_after_parse() == "ada"
  ✓ assert reparse().prefs[0] == "dark"

6 tests: 6 passed, 0 failed
$ soma verify json_roundtrip.cell
Verifying json_roundtrip.cell...
No state machine in this program: nothing to prove beyond `soma check` (invariants and lifecycles are what verify proves).
VERIFY OK (vacuous — no state machine)

Builtins used

contains, from_json, is_a, list, to_json

Source file: /corpus/records/json_roundtrip.cell · examples/corpus/records/json_roundtrip.cell