GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — jett/docs/active/stdlib_json_extraction_plan.md at main · vycdev/jett

Expand file tree

/

stdlib_json_extraction_plan.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
415 lines (368 loc) · 23.8 KB
/

stdlib_json_extraction_plan.md

Copy path

File metadata and controls

415 lines (368 loc) · 23.8 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

JSON Stdlib Extraction Plan

This note records the remaining compiler/tooling boundaries around the reflected JSON stdlib. The reflected prototypes now live in stdlib/json/; what remains is deciding which compiler-owned policy gates and compatibility bridges should eventually become ordinary language/library mechanisms.

The important conclusion is that JSON itself is no longer the main blocker. Reflection can now read fields, construct structs/bitfields/enums, inspect type arguments, use structured kind and primitive tags, and walk native JsonTree values. json.JsonTree is the canonical raw type. The legacy compiler-owned JsonValue primitive, bootstrap fallback, and bare root alias have been removed; both bare JsonValue and json.JsonValue are always unknown. The remaining boundary is the module and namespace path that would let ordinary .jett stdlib code carry the compiler-owned policy behind the public json.* API.

Current Architecture

  • stdlib/ now has a bootstrap loader, marker module, and draft JSON module.
  • build_file parses the requested file, then prepends stdlib modules and, when a jett.proj is discovered, sibling project modules.
  • run_file validates through build_file, then registers stdlib modules, sibling project modules, and the entry module in the interpreter.
  • build_source and test_file also prepend stdlib modules, so LSP-style validation and jett test file exercise the same prelude path.
  • test_file now also loads sibling project modules for cross-file verify blocks, while stripping verify/property blocks from support modules so a single-file test report stays focused on the requested file.
  • Namespaces are parsed and resolved as declarations. Top-level functions and named types are checked and interpreted through canonical namespace.name names, with scoped lookup preserving same-namespace ergonomics. This is still lighter than a full module registry, but it no longer relies on runtime flat leaf aliases for namespaced declarations.
  • use declarations bind aliases or final path segments, but they do not yet import a namespace registry.
  • Builtin module prefixes such as json, type, list, map, set, string, and bytes still have compiler-aware resolver/typechecker/ interpreter paths. For JSON, the compiler-owned policy surface is now narrow: json.parse, json.parse_exact, json.serialize, and json.serialize_public keep policy-first typechecking, while raw facade signatures come from exported stdlib wrappers. Set builtins still have compiler-owned signatures for new/add/remove/contains/length/is_empty/to_list/union/ intersection/difference, so JSON set parsing fixtures typecheck through normal builtin signatures. This compiler-backed public surface is transitional technical debt: every public set.* declaration and signature must ultimately move to compiler-shipped .jett source, and the compiler must not retain hardcoded public set names or signatures. Public source declarations may delegate equality, storage, cardinality, iteration, and conversion to private trusted runtime kernels, but those kernels remain implementation details. Extracting the first compositional is_empty, union, intersection, and difference slice into real Jett bodies is tracked by #59; follow-up remains for public new, add, remove, contains, length, and to_list declarations.
  • The compiler-backed public map.* surface is transitional technical debt. The final boundary requires every public map declaration and signature to come from compiler-shipped .jett source, with compositional operations implemented by real Jett bodies and no compiler dispatch by public name. #61 is the first bounded slice for is_empty, contains_key, set, get_or, and merge. Follow-up extraction must source-own the remaining public constructors, accessors, mutations, conversions, iteration helpers, and higher-order operations. Storage, key equality, lookup/update, and iteration may use private trusted runtime kernels, but those kernels are implementation details rather than public compiler-owned functions.

That means physical stdlib JSON fragments under stdlib/json/ are available to single-file builds, but ordinary namespace json functions still do not automatically own policy-bearing public calls such as json.parse[T](...).

JSON-Specific State

The reflected JSON implementation now lives in stdlib under the json namespace. Prefixed hook names hold the trusted implementation bodies:

  • stdlib/json/ fragments
  • JsonTree as a first self-hosted raw JSON tree representation
  • json_tree_serialize(value: JsonTree)
  • json_tree_parse(raw: string) for staged scalar, array, and object parsing
  • json_tree_* traversal helpers for kind checks, field/index lookup, lengths, keys, and scalar casts including full-range uint64
  • json_serialize_reflected[T](view value)
  • json_serialize_public_reflected[T](view value)
  • json_parse_reflected[T](raw: string)
  • json_parse_exact_reflected[T](raw: string)

The module also declares exported public wrapper names parse, parse_exact, serialize, and serialize_public. Calls such as json.parse[T](raw) and json.parse_exact[T](raw) still pass through the compiler-owned policy gate first. The interpreter requires both the trusted internal reflected hook and the trusted exported public wrapper, then executes the public wrapper as the runtime body boundary. The private hook names remain the trusted implementation targets inside the wrapper body until the language can carry the compiler-owned JSON policy on ordinary stdlib declarations.

The typed parse and serialize bridge hooks are exercised indirectly through trusted exported public wrappers. Ordinary source can name the exported json.json_tree_parse raw parser, but cannot name the private reflected hook entrypoints directly; compile-fail fixtures pin that visibility boundary.

The run-pass fixtures now act as parity and shape coverage for the stdlib implementation. They still own test-specific type definitions and small model helpers:

  • tests/run_pass/json_reflection_nested_serializer.jett
  • tests/run_pass/json_reflection_nested_decoder.jett

Together they cover the shapes that the current stdlib module must preserve:

  • recursive structured type dispatch through TypeKind and TypePrimitive,
  • primitive values, bytes, null, aliases, refinements, secrets,
  • structs, bitfields, enum variants and enum payloads,
  • lists, sets, map[string, V], optionals, and results,
  • field serialize_name,
  • missing optional defaults,
  • public secret omission for the serializer prototype,
  • all-control-character JSON string escaping in .jett.
  • self-hosted JsonTree construction, serialization, staged scalar/array/object parsing, and traversal helpers for the future raw parser target.
  • bridge checks that keep the reflected prototypes aligned with the public JSON facade for representative full serialization, public serialization, and typed parse.
  • focused external shape fixtures for bytes, floats, primitive sets, maps, enum payloads, bitfields, optionals, results, refinements, and public secret omission across serialize, serialize_public, parse, and parse_exact.
  • malformed-input parity across json.json_tree_parse, json.parse_raw, json.parse[json.JsonTree], and the exact raw-tree target.
  • dedicated shape coverage now lives in json_shape_matrix, json_parse_collection_edges, json_parse_exact*, json_enum_bitfield_exact_edges, json_refinement_exact_serialize_edges, json_parse_exact_secret_edges, json_tree_reflection_construction, and parser parity fixtures.

The compiler-known JSON bridge remains the compatibility and policy facade. It still owns the public typechecker policy for json.parse, json.parse_exact, json.serialize, and json.serialize_public. In the interpreter, all four public calls now require trusted private hook entries and trusted exported public wrappers from compiler-shipped stdlib files, then execute the public wrapper bodies. The old typed Rust fallback paths for public parse/serialize have been removed; Rust-backed paths have also been removed from raw JSON execution in jett_comptime. Public json.parse_raw now runs through the exported stdlib wrapper around the self-hosted JsonTree parser, and raw helper calls dispatch native JsonTree runtime values through exported stdlib facade wrappers that call json_tree_* helpers. The old compiler-owned raw facade fallback dispatcher has been removed; in no-stdlib direct-interpreter contexts the raw public names are ordinary undefined functions instead of hidden Rust-backed JSON semantics. json.parse_exact[T] now exists as a second compiler-policy public parse bridge backed by trusted stdlib hooks. It rejects unknown object fields recursively for reflected closed-shape targets: structs, bitfields, enum payloads, aliases/refinements over those shapes, and containers containing them. Raw json.JsonTree targets remain arbitrary JSON payloads. The existing json.parse[T] behavior remains lenient.

Remaining Boundaries

1. Stdlib Loading

The driver loads stdlib .jett files before user modules for:

  • jett build,
  • jett run,
  • jett test file,
  • jett test over a project,
  • LSP validation paths,
  • future query/agent tooling.

This is still intentionally simple: files are collected from repo-local stdlib/ and prepended before project modules. Dependency ordering is lexical for now.

Status: implemented for the current single-file, project, test, and LSP-style entrypoints. The remaining language work is a real module/import registry and a less lexical dependency model, not JSON-specific stdlib loading.

2. Public json.* Handoff

The module/import/prelude and backend-neutral trusted-origin decision is recorded in the module and trusted-origin contract from #3. The registry and lowering stages remain unimplemented.

Generic and non-generic user functions can now be called through a qualified namespace name such as helpers.wrap[T](value) or json.json_parse_reflected[T](raw).

Moving JSON fully into ordinary .jett declarations still needs a policy-aware public API handoff:

  • the compiler-owned json.parse, json.parse_exact, json.serialize, and json.serialize_public paths still carry compiler-enforced policy checks,
  • use now gates executable access to project and vendored namespaces, but it still resolves against the merged lexical scope rather than the selected module registry with backend-neutral identity and dependency metadata,
  • canonical qualified declarations and export visibility now exist, but the language still lacks a real module/import registry and dependency model.

This is larger than JSON and is staged by the selected contract. See /docs/active/stdlib_visibility_design.md for the current visibility and trusted-stdlib recommendation.

The important design boundary is now explicit: export and trusted stdlib origin are separate. export controls what ordinary source code can name. Trusted origin controls whether compiler-owned JSON policy may delegate to a stdlib implementation. A private trusted hook is valid as a compiler target; an exported user/project function with the same name is not.

3. Builtin Policy Boundaries

Some JSON rules are typechecker policy, not only implementation:

  • json.serialize[T] and json.serialize_public[T] require view for non-copy compound values.
  • full serialization rejects secret-containing values.
  • public serialization rejects top-level secret wrappers and omits secret-containing fields.
  • map[K, V] JSON encoding and decoding for serialize, serialize_public, parse, and parse_exact is restricted to K == string.
  • serialization and parsing reject non-data values that have no JSON encoding or decoding, including functions, actors, interfaces, and the internal TypeConstruction builder. Machine values use the canonical state/payload envelope for both parse and serialize when every payload field is JSON-compatible. Parse checks descend through secret[...] wrappers because secret data still has to be constructed from JSON.
  • json.parse[T] and json.parse_exact[T] return result[T, string], so callers must handle errors.

Those checks can remain compiler-known while the body moves to .jett, or they can be redesigned as ordinary typed stdlib constraints later. The safer staging choice is to keep the checks until the module/import story can carry those constraints deliberately.

Status: implemented for the interpreter/runtime path through trusted bundled hooks. The selected registry preserves the gates through canonical trusted declaration identities. Whether the public policy gates can become ordinary stdlib constraints remains a separate decision after that identity reaches future backends.

4. Visibility

The serializer and decoder need helper functions such as quote, decode_value[T], and enum/field helpers. Jett now has explicit export visibility for namespaced declarations. Unexported namespace declarations are hidden from ordinary source and tooling completions, while compiler-owned JSON policy may still delegate to trusted private hooks.

The current stdlib uses export for the intended public surface and leaves internal hooks unexported. This is enough for the current JSON module, but it is not a full module/import privacy story.

Trusted origin remains separate from visibility: interpreter function registry entries parsed from the reserved stdlib file-id range are marked trusted, and public JSON bridges require trusted hook entries. This solves bridge spoofing for current JSON hooks; future backends need the same identity boundary.

Current Staging Record

  1. Keep the compiler-known public JSON bridge for policy checks.
  2. Continue staging extracted prototype code under namespace-private, prefixed implementation names:
    • json_serialize_reflected[T](view value: T) exists in stdlib.
    • json_serialize_public_reflected[T](view value: T) exists in stdlib.
    • json_decode_tree_reflected[T](view raw: JsonTree) exists in stdlib.
    • The old private raw-value decoder wrapper and the duplicate raw decoder helper family have been removed.
    • json_parse_reflected[T](raw: string) now routes typed targets through the self-hosted JsonTree parser/decoder.
    • Public raw facade wrappers now exist in stdlib/json/ for parse_raw, serialize_raw, tree kind/predicates, lookup, length/key helpers, and scalar casts.
    • The typechecker raw facade signatures now come from those exported stdlib wrapper declarations. The hardcoded raw facade signature fallback and the old typechecker-only compatibility table and root alias have been removed.
    • json_tree_serialize is view-native and iterates arrays/objects through viewed list/map loops, so serialize_raw(view value) no longer clones the tree before serializing.
    • The JSON facade name policy is centralized in jett_common and reused by runtime wrapper precedence plus ownership checking, including direct view-first json_tree_* helpers. Raw facade entries are now a public name set rather than a trusted hook/argument-shape dispatch table.
    • The compiler-policy public bridge names (json.parse, json.parse_exact, json.serialize, and json.serialize_public) also share their trusted private hook mapping through jett_common, while runtime execution goes through the corresponding trusted exported wrapper.
  3. Maintain the public bridge handoff. json.parse, json.parse_exact, json.serialize, and json.serialize_public now use compiler-owned typechecker policy with stdlib-owned interpreter bodies. See /docs/completed/json_public_bridge_handoff.md.
  4. Keep the real public wrapper names in namespace json, while retaining compiler policy checks for secrets, view, map keys, unsupported parse/serialize target types, and handled results.
  5. Keep broad bridge/parity tests around removed Rust-backed fallback paths and the current trusted-wrapper/error paths. Done for typed public parse/serialize and raw json.JsonTree execution in jett_comptime, and runtime main() reflection metadata handoff for namespaced generic JSON. Public policy coverage now also pins unsupported parse/parse_exact and serialize/serialize_public targets through direct, secret, wrapper/container, enum-payload, machine/state-machine, and TypeConstruction paths.
  6. Continue hardening the self-hosted JsonTree parser. Common malformed-input diagnostics are pinned for unterminated strings/arrays/objects, trailing characters, mismatched delimiters, bad number forms, bad literals, empty/whitespace-only roots, malformed object keys, duplicate object fields after key unescaping, comma/separator errors, extra closing delimiters, nested unterminated strings, invalid escapes, and unicode surrogate failures. Root and nested value trimming now follows JSON's byte-level whitespace set only: space, tab, line feed, and carriage return. Non-JSON whitespace such as form feed stays part of the token and is rejected through the same parser error path as other malformed input. Valid JSON escapes now include quote, backslash, slash, backspace, form feed, newline, carriage return, tab, and unicode escapes. Public entrypoint parity for those parser errors is pinned across json.json_tree_parse, json.parse_raw, json.parse[json.JsonTree], and json.parse_exact[json.JsonTree]; success parity covers representative null, bool, number, string, empty-container, and nested compound roots across the same public raw entrypoints. Container parsing now recurses through byte spans for nested array/object values instead of converting every segment back into a string and reparsing from bytes; string scalar values and object keys now parse from byte spans as well, and string unescaping now appends unescaped byte chunks rather than slicing one byte at a time. Literal and number scalar dispatch is also byte-span based, materializing a string only for the raw number spelling stored in JsonTree.number_value. The strict raw lookup helpers are shared at the private JsonTree layer by public wrappers, reflected decoding, and exact validation.
  7. Keep the completed alias retirement pinned. Bare JsonValue, json.JsonValue, root type aliases, and the compiler-owned primitive have been removed. See /docs/completed/json_value_transition_plan.md and /docs/completed/root_alias_policy.md.
  8. Keep reflection-specialized generic helpers staged carefully. The typechecker now checks ordinary generic function bodies per concrete instantiation, and it can specialize the narrow direct-branch form type.kind_tag[T]() / type.info[T]().kind_tag compared to TypeKind.* inside if/else if conditions. It also carries immutable block-local TypeInfo, TypeKind, and TypePrimitive facts derived from those direct reflection calls, so helpers may name TypeInfo info = type.info[T]() and branch on info.kind_tag, info.primitive_tag handle default ..., or local tag variables. Immutable generic helper parameters of type TypeInfo, TypeKind, or TypePrimitive also receive those facts from known call arguments, which lets helper split points like json_decode_tree_structured_reflected[T](..., kind, ...) and primitive decoder helpers specialize on caller-reflected tags. Branches selected by a statically known reflection guard may now contain deeper type.arg[T](...) bindings, while unknown/runtime guards are rejected instead of falling back to checking all branches. Direct top-level type.arg[T](...) bindings are also checked per concrete generic instantiation, which brings shape-specific helpers such as list/map/optional/result JSON helpers into the typed path. Direct reflected type.fields[T](), type.variants[T](), and type.machine_states[T]() loops are also checked per concrete owner in top-level helpers or selected reflection branches, which pulls record, enum, and machine JSON helper bodies further into the checked path. Direct top-level value-sensitive reflection statements for variant/state selection and TypeConstruction start/finish are checked per concrete instantiation as well. Reflection-specialized match statements over known TypeKind and TypePrimitive values now select only the reachable arm, matching Jett's canonical enum-dispatch form rather than forcing all generic reflection code through if ladders. Primitive JSON dispatch still keeps exact TypePrimitive.* comparisons visible where a branch chooses a different runtime carrier such as uint64; narrow classifier helpers are allowed only when every selected primitive shares the same safe cast target, such as the int64-backed integer path. This keeps invalid primitive casts prunable while giving stdlib code headroom under the function complexity checker. Predicate-derived facts, diagnostic string facts, and other value-sensitive reflection helper shapes remain deferred.

Recommended Shape For The Stdlib JSON Module

The eventual module should keep these layers distinct:

  • quote(raw: string) returns string
  • serialize_value[T](view value: T) returns result[string, string]
  • serialize_public_value[T](view value: T) returns result[string, string]
  • decode_value[T](view raw: JsonTree) returns result[T, string]
  • parse[T](raw: string) returns result[T, string]
  • parse_exact[T](raw: string) returns result[T, string]

The public API can return plain string for serialization only if the compiler continues to prove that the chosen policy cannot fail. The internal reflected functions should probably use result while format policy is still evolving.

Resolved Raw Lookup Guidance

Raw JSON lookup naming and default usage guidance were finalized in #5. json.field and json.index remain stable probing helpers for exploratory traversal. Production validation should use json.object_field / json.array_index when absence is allowed and json.require_field / json.require_index when presence is required. There is no planned deprecation of the probing helpers; any later removal would require an explicit deprecation mechanism and a separate compatibility decision.

Open Questions

  • Should json.serialize[T] stay a compiler-checked secret exposure boundary even after its implementation body moves to stdlib code?
  • Should unknown object fields be ignored, rejected, or configurable? See docs/open_design/json_unknown_field_policy.md for the staged parse_exact path, now implemented while keeping json.parse[T] lenient.
  • Representative shape is pinned for bytes, float32/float64, primitive sets, maps, optionals/results, unit and payload enums, bitfields, aliases/refinements, serialize names, and nested matrix combinations. The remaining shape questions are narrower: whether map/set ordering should ever become a documented contract, whether to add configurable strictness beyond parse_exact, and whether more parser diagnostics deserve similarly specific wording.
  • How should stdlib helper visibility evolve beyond namespace-private export syntax, especially once a full import/prelude model exists?
  • How much abstraction is allowed around trusted reflection loops before comptime type Field = field.type_info: loses provenance?
  • How much shared helper extraction is safe inside large mutual groups? Exact validation and decode now both share list/set array traversal through generic helpers, so the remaining caution is around helpers that must preserve TypeInfo or TypeField provenance through nested reflection loops.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.