WEP: Jade — JSON Schema for Wado
Context
The first consumer of Jade is an HTTP framework in the style of FastAPI. A handler takes and returns typed values, the framework decodes the request body into the handler's argument, and it publishes an OpenAPI document that describes every body. OpenAPI 3.1 describes a body with JSON Schema Draft 2020-12, so the framework needs one schema per Wado type. Every value the server writes has to validate against it, and every document that validates has to decode, or the published API and the served one drift apart.
"JSON Schema" names four separate capabilities, and keeping them apart is the first design step:
| Capability | Input → output | Rust prior art | Go prior art | |
|---|---|---|---|---|
| A | Schema document model + I/O | JSON Schema document ⇄ typed tree | schemars::schema |
invopop/jsonschema Schema |
| B | Type → schema derivation | Wado type → schema document | schemars | invopop/jsonschema (struct-tag reflection) |
| C | Schema → value validation | (schema, JSON document) → result | the jsonschema crate |
santhosh-tekuri/jsonschema |
| D | Schema → Wado type codegen | .json schema → generated .wado |
typify | go-jsonschema |
A framework that starts from typed handlers needs B. The others serve programs that start from a schema someone else wrote.
Wado already has the pieces these ecosystems add after the fact:
core:serde's derivedSerializeandDeserialize, with#[wire(…)]and field defaults. A derived schema reads the same facts the decoder reads.- Static Reflection: a library walks a type's members
with an ordinary generic
impl, ascore:serdeitself does. - Refined Types: a value's permitted range
is a contract clause on its type, enforced by the language. A value clause is
also readable through reflection.
i32 contract 0..=150is checked by the derivedDeserializeand becomesminimum: 0, maximum: 150in the schema. - Kiln: D is a generator, as Gale and Grog are.
core:temporal,core:urlandcore:uuid, which supply theformatvalues other ecosystems reimplement.
What changed since the first version
The first version of this WEP took the options of a Kiln generator as its first
consumer. Those options now cross the generator boundary as a typed WIT value,
so they need no schema. It also proposed a Constrained trait for a value's
permitted range. Nothing enforced that trait at a boundary, and Jade could not
implement Deserialize for a type it does not own. Refined types replace it.
Decision
Name
Jade: JSON Assertion and Definition Engine. Assertion is C, definition is A, B
and D, and the engine is the runtime and the generator together. It is a short
natural noun, as Gale, Kiln, Grog, Marl and Loam are. The package is
wado-lang:jade.
One package, four layers
Jade is a library and, for D, a Kiln generator, in one package, as Grog is. Each layer is usable on its own, and no layer depends on one above it:
D codegen .json schema → .wado types (Kiln generator)
C validation (Schema, document) → result
B derivation JsonSchema: T → Schema (library code over Reflect*)
A model Schema (written through core:serde to core:json)
Nothing of JSON Schema is in the compiler or the standard library.
Layer A — the schema model
A schema is true, false or an object, so Schema is a variant of
Bool(bool) and Object(SchemaObject). SchemaObject is a typed struct with
one field per Draft 2020-12 keyword, written through core:serde to
core:json. An absent keyword is left out of the output rather than written as
null. core:serde has no way to omit a field by its value, so
SchemaObject writes itself with a hand-written Serialize. A keyword the
draft does not define is kept as written, in extra.
The model is typed rather than a tree of core:value::Value. A Value tree is
slow to build and to walk, and the schemas B emits are known keyword by
keyword.
Schema::parse reads a schema from JSON text. A keyword whose value breaks the
draft's rule for it is an error at its JSON Pointer.
The document model
Jade reads two kinds of JSON without decoding them into a Wado type: a schema's
text, and an instance C validates. Both are read into a Document. A
Document holds its values in flat arrays in document order, one array per
field, so reading one allocates a few arrays rather than one object per value.
A Node is a value inside it. Its equality is JSON Schema's: 1 equals 1.0,
and an object's members compare whatever their order. The keywords that hold
any JSON value (default, enum, const and examples) hold a Document.
A Document is read through core:json's lexer, so it settles what RFC 8259
leaves open as core:json does. A repeated key and a lone surrogate are
errors.
A number is a Number, held exactly whatever its size and precision
(Validation §4.2), and two compare by their mathematical value. Most numbers are
the shortest decimal of an f64, which tells them apart and orders them as they
are ordered, so a Document keeps those as f64s. Only a number no f64 holds
that way carries its digits. An exponent of more than 18 digits is an error:
nobody writes one, and the bound keeps every exponent Jade computes within an
i64.
Layer B — deriving a schema from a type
pub trait JsonSchema with () {
fn json_schema(gen: &mut SchemaGenerator) -> Schema;
}
impl SchemaGenerator {
pub fn new() -> SchemaGenerator; // definitions under `#/$defs/`
pub fn openapi() -> SchemaGenerator; // under `#/components/schemas/`
pub fn define(&mut self, name: String, build: fn(&mut SchemaGenerator) -> Schema) -> Schema;
}
pub fn schema_for<T: JsonSchema>() -> Schema; // a standalone document
The trait has no receiver, so a schema is built from the type alone.
SchemaGenerator collects the definitions a schema refers to and decides where
they live. define emits a named composite once as a definition and answers a
$ref to it at each use. It records the name before building, which is also
how a recursive type such as struct Node { next: Option<Node> } ends. A
composite whose name is empty, such as an anonymous struct, is built inline.
The name is Reflect::decl_name(), so the trait needs no schema_name of its
own.
One blanket per kind
Jade derives JsonSchema with one blanket impl per reflection kind, as
core:serde derives Serialize:
impl<T: ReflectStruct<FieldTypes = [..F], FieldInputs = [..F]>, ..F: JsonSchema> JsonSchema for T { … }
impl<V: ReflectVariant<CasePayloads = [..P]>, ..P: JsonSchema> JsonSchema for V { … }
impl<E: ReflectEnum<Members = [..M]>, ..M> JsonSchema for E { … }
impl<L: ReflectFlags<Members = [..M]>, ..M> JsonSchema for L { … }
impl<R: ReflectRefined<Base = B, …>, B: JsonSchema, …> JsonSchema for R { … }
The struct blanket pins FieldInputs, as serde's do, so a closed struct (one
with a field narrower than the struct) derives no schema, just as it derives no
Serialize. Its author writes both
(Reflect Derivation).
A newtype inherits its base's impl, as it inherits every trait. The leaves are
Jade's own impls: the primitives, String, the byte types, Option, List,
TreeSet, HashSet, TreeMap, HashMap, Result and the tuples. So are
the standard library types whose Serialize is hand-written: core:temporal's
types, core:uri's Uri and UriReference, core:url's Url and
core:uuid's Uuid, each a string, and core:value's Value, which is any
JSON value.
A leaf takes a format only when every text its type writes meets that format,
read strictly, and Jade writes no format name the specification does not
define. So Uri takes uri, UriReference takes uri-reference and Uuid
takes uuid, while the core:temporal types take none: an Instant or a
PlainDate may carry an expanded year that RFC 3339 rejects, a Duration such
as P1Y2D or PT0.5S falls outside RFC 3339 Appendix A's grammar, and the
other types write a time without an offset or with a time zone annotation.
package-jade/ records what the specifications and implementations say.
Each of these leaves but Value also names its Wado type in x-wado-format,
in Symbol Notation:
{"type": "string", "x-wado-format": "core:temporal#Instant"}. JSON Schema
reserves the x- prefix for annotations, which other tools ignore and which
must not affect evaluation. So C never asserts it, and D reads it before
format to choose the type it generates.
Total Reflection's match type would
fold the blankets into one body. The blankets are what exists today.
The schema follows the wire form
Each kind maps to the shape core:json writes
(Serialization). The derived Deserialize reads
that shape and sometimes more, such as a number spelled as a string. A document
that matches the schema decodes, apart from the gaps kept in package-jade/,
such as the text a leaf asserts nothing about. The kinds map as follows:
| Wado | JSON Schema |
|---|---|
bool |
boolean |
i8…i32, u8…u32 |
integer, bounded by the type's range |
i64, u64 |
integer in the type's range and within ±(2^53 − 1), or a decimal string in the type's range |
i128, u128 |
a decimal string in the type's range |
| the float types | number |
char |
string of one code point |
String |
string |
ByteList, ByteArray, ByteSlice |
string with contentEncoding: "base64url", unpadded |
the core:temporal types |
string with x-wado-format |
Uri |
string with format: "uri" and x-wado-format |
UriReference |
string with format: "uri-reference" and x-wado-format |
Uuid |
string with format: "uuid" and x-wado-format |
Url |
string with x-wado-format |
() |
null |
core:value's Value |
true |
Option<T> |
anyOf of T's schema and null |
List<T> |
array of T |
TreeSet<T>, HashSet<T> |
array of T with uniqueItems |
TreeMap<String, V>, HashMap<String, V> |
object whose additionalProperties is V's schema |
| a tuple | array with prefixItems, and minItems and maxItems both its arity |
struct |
object: properties under the wire names, required, each field's default |
enum |
string with enum of the wire names |
flags |
array of the member wire names, with uniqueItems |
variant |
oneOf: a unit case as a const string, a payload case as an object of that one property |
variant with #[wire(tag)] |
oneOf of objects whose tag property is the case's const wire name |
| newtype | its base's schema |
| refined type | its base's schema, with the keywords its clauses carry |
A decimal string's range is a pattern anchored by ^ and $, since a
regular expression states any integer range exactly and JSON Schema does not
anchor one itself. The pattern uses plain groups and [0-9] alone, the subset
every engine reads alike. An Option takes anyOf rather than oneOf, because
in Option<Option<T>> both branches accept null.
A tuple bounds its length on both sides: items: false alone admits a shorter
array, which the decoder rejects. A payload case's object takes
maxProperties: 1, since the decoder rejects a second key there too.
A field is required when it declares no default. A field with a default takes
the default keyword, its default value written as core:json writes it, or
none where JSON cannot hold the value, such as NaN. A bare Option<T> field is
required and may be null; an Option<T> = null field is optional.
A derived Deserialize skips a key that names no field. The derived schema
therefore leaves additionalProperties unset rather than false, so a client
may send a field that a newer server reads and this one ignores.
Refined types become assertion keywords
A refined type's value clauses carry its keywords. Jade reads them through
ReflectRefined and its own Keywords trait, which it implements for the
standard library's clause types: a range becomes minimum and maximum, or
exclusiveMaximum for an exclusive one. Length { min, max } becomes
minLength and maxLength only if it counts code points, as those keywords do;
what it counts is a known gap of Refined Types. A clause type that implements
Keywords in its own package reaches the schema the same way.
type UserName = String contract Length { min: 1, max: 64 };
type Age = i32 contract 0..=150;
#[wire(name_policy = "camelCase")]
struct CreateUser {
/// The user's login name.
user_name: UserName, // {"type": "string", "minLength": 1, "maxLength": 64}
age: Age = Age::from(0), // {"type": "integer", "minimum": 0, "maximum": 150,
// "default": 0}; not required
}
Doc comments become title and description
title and description come from /// doc comments, through
Reflect::doc() and Member::doc()
(Doc Comments). A definition takes its
type's comment, a property its field's, and a variant's oneOf branch its
case's. A property that is a $ref carries its field's comment beside the
$ref, where it wins over the definition's. When a comment has more than one
paragraph and the first is a single line, that line is the title and the rest
the description. Otherwise the whole comment is the description.
Use from a framework
A handler's signature is not reflectable, but its function type is enough. A route registration bounds the handler's argument and result, and inference settles both from the handler:
fn post<Req: JsonSchema + Deserialize, Res: JsonSchema + Serialize, effect E>(
&mut self, path: String, handler: fn(Req) -> Res with E,
) { … }
app.post("/users", create_user); // Req = CreateUser, Res = User
The framework decodes a request body with the derived Deserialize, which
enforces every refined field through try_from. A failed clause is a
DeserializeError with the path to the field, which the framework answers with
a client error. It never traps.
Layer C — validating a document
C checks a JSON document against a schema it did not derive, such as a third party's. Its commitments stand from the first version:
- Compile once, validate many.
compileresolves every local$ref,$defsand anchor into a table up front. - Errors are keyed by JSON Pointer, into the document and into the schema.
formatasserts the grammar the specification cites, read strictly, behind a flag, since the specification makesformatan annotation by default.- A remote
$refresolves only among the documents the caller supplies, or that a loader the caller passes fetches, so the validator performs no effect of its own. patternneeds a regular expression engine. Its subset is documented, and an unsupported construct is an error atcompile, never a silent pass.
let validator = Validator::compile(&Schema::parse(text)?)?; // CompileError
validator.validate(&doc.root()) // Result<(), List<ValidationError>>
A SchemaSet holds the documents a schema's references reach, each under the
URI it was retrieved from. compile_loading fetches each document that
compiling the one under base needs and the set lacks, through a loader the
caller passes, and compiles it. The loader's effects are the caller's, and
whether it reads the network, a mirror or a local copy is the loader's to
decide:
let mut set = SchemaSet::new();
set.insert(base, root);
let validator = Validator::compile_loading(&mut set, &base, fetch)?; // LoadError<E>
It fails with LoadError::Failed when the loader does, naming the URI and
carrying the loader's error, and with LoadError::Invalid when a document
breaks a rule. The documents fetched stay in the set, so compiling another of
its documents fetches none twice. SchemaSet::load fetches the same documents
without compiling, for a caller that only gathers them. The loader may keep
state, such as a cache, and may wait on an asynchronous call, such as an HTTP
request, so a caller needs no other way to supply a document.
compile_in resolves the references of the document named and of the
documents its references reach, so a reference nothing reaches is no error. A
reference takes the document retrieved from the URI it names. Failing that, it
takes every supplied document, since any of them may identify the URI by an
$id. Each of those is checked against its keywords' rules, so one that breaks
a rule is an error: a document Jade cannot read might be the one that
identifies the URI. A reference reaches Draft 2020-12's meta-schemas without
their being supplied.
compile fails with CompileError::Invalid, a
SchemaError, when a document breaks a rule, and with
CompileError::Unresolved when a reference names a document nobody supplied.
An error names the document by the URI it was supplied under, and names none
for the schema compile was given alone.
compile lays the subschemas out in one table, indexed by their $id, their
anchors and their JSON Pointer under each resource that holds them, and points
every $ref at an index. A schema without an $id takes an internal base URI,
which resolves relative references as any other base does. validate reports
every keyword the instance fails, but under anyOf, oneOf, not and if
only the keyword itself, since a failing branch is not an error.
A $ref or $dynamicRef that comes back to a subschema at the value it left,
without stepping into the instance, would recurse forever. The specification
leaves such a schema undefined, and validate reports the reference that
closes the cycle as failing.
References do not multiply the work of evaluation. A subschema that allOf
reaches through two references, at each of n levels, would otherwise be
evaluated 2^n times at one value. Evaluating a subschema at a
value gives the same answer each time while the dynamic scope binds every
$dynamicAnchor alike. So where more than one keyword leads to a subschema, a
reference to it evaluates it once per value and per binding, and every other
reference reuses the outcome. What it evaluated is gathered as a set, so reuse
does not grow it either. validate reports each error once, however many
references lead to the keyword that raised it.
A URI identifies at most one schema, so two schemas claiming one URI, by $id
or by an anchor, are an error at compile.
multipleOf divides the decimals as written, so 0.3 is a multiple of 0.1,
though not in binary floating point.
pattern and patternProperties use lib:re, which reads ECMA-262 patterns
in Unicode mode and rejects what it cannot match in linear time: a
backreference.
format is an annotation unless the caller compiles with
CompileOptions { assert_format: true }, which each compile takes as its
last argument. Then a string whose format Jade asserts must match that format's
grammar, read strictly. A format Jade does not assert, whether the
specification defines it or not, passes every string, as Validation 7.2.1
permits. Jade asserts date-time, date, time, duration, email,
ipv4, ipv6, uri, uri-reference, iri, iri-reference, uuid,
uri-template, json-pointer, relative-json-pointer and regex. A
regex is held to ECMA-262's syntax alone, through Re's
validate_ecma262_syntax, so a backreference passes though pattern rejects
it.
let validator = Validator::compile(&schema, CompileOptions { assert_format: true })?;
Layer D — generating Wado types from a schema
D is a Kiln generator. The code it writes uses core:serde's derived
Serialize and Deserialize and nothing of Jade's, so the consumer names Jade
under [build-dependencies] alone.
use { CreateUser, Address } from "./api.schema.json" with {
generator: { module: "lib:jade" },
};
D reads the schema as C does: through A's reader, Draft 2020-12 alone. It writes
one module, through lib:wadopoet. A remote $ref resolves among the files the
use lists under inputs, through a SchemaSet, and the declarations it
reaches are written into the same module.
The SchemaSet holds each file, the imported one included, under a file: URI
built from the path Kiln hands D, which Kiln resolves against the declaring
.wado file. Each path segment is percent-encoded into the URI, as RFC 3986
admits only ASCII, so a file name with a space or outside ASCII has a URI too.
In a file with no $id, a relative $ref such as ./address.schema.json
resolves against that URI, and so names the file beside it on disk. In a file
with an $id, it resolves against the $id, as Draft 2020-12 says, and names
a file only where one declares the resulting $id, which C's search of every
document's $id finds.
Each $defs entry becomes a pub declaration named by its key. A root that
holds a $ref and nothing else but $schema and $defs, as schema_for
writes it, declares nothing more. Any other root
takes the first name it finds: the root option, then title, then the file's
name (create-user.schema.json → CreateUser). An object nested without a
name takes its parent's name and its field's (CreateUserAddress).
D reads B's table backwards:
| JSON Schema | Wado |
|---|---|
a string with an x-wado-format D can resolve |
the type it names |
integer bounded by exactly an integer type's range |
that type, i8…u32 |
B's shape for i64, u64, i128 or u128 |
that type |
integer with no bounds |
i64 |
number |
f64 |
string with format uuid, uri or uri-reference |
Uuid, Uri, UriReference |
string with format: "date-time" |
Instant |
string with contentEncoding: "base64url" |
ByteList |
any other string |
String |
null |
() |
anyOf of T and null, or type: [T, "null"] |
Option<T> |
array |
List<T> |
array with uniqueItems |
TreeSet<T> |
array with prefixItems, and minItems and maxItems its arity |
a tuple |
object with additionalProperties alone |
TreeMap<String, V> |
object with properties |
struct |
enum of strings |
enum |
a definition of B's shape for flags |
flags |
B's shape for Result |
Result<T, E> |
B's shapes of oneOf, tagged or not |
variant |
true, {} |
core:value's Value |
$ref |
the declaration it names |
x-wado-format comes before format, and names a type only in core:*, which
every consumer can import. A format gives a type only where that type reads
every string the format admits and writes only such strings, the rule B's
leaves follow, with date-time as the one exception.
An array with uniqueItems whose items are an enum of strings is a flags
only where it is a definition of its own, as B writes one, and only where its
members' wire names all come back under one name_policy, as a flags member
takes no #[wire(name)], and of at most 32 members, as a flags value is one
u32. Otherwise it is a TreeSet of an enum. Result is
told apart from a variant by its two cases, Ok and Err, each B's payload
shape.
A field the schema does not list as required takes its default where it has
one, and is Option<T> = null otherwise. A description becomes the doc
comment, after the title where there is one, which is how B reads a comment
back. A struct, enum or variant written in place takes no doc comment: its
property's description is the field's.
A default is written as a literal where its type has one: a boolean, a number,
a string, null, or an enum member. Any other default is decoded from its JSON
text where the field is constructed. Draft 2020-12 lets a default be any value,
but a field holds only what its type does, so a default the property's own
schema rejects, its format asserted, is an error.
A name in a schema is free text, such as Create user (v2). D splits it into
words at each change of case and at each character that is not an ASCII letter
or digit, and drops those characters, as a Wado identifier is ASCII. A
declaration and an enum member join the words in PascalCase, keeping each
word's case after its first letter, so HTTPServer stays HTTPServer. A field
joins them in snake_case. A type whose wire names all come back from their Wado
names under one name_policy takes that policy, chosen per type; otherwise each
name that does not come back takes #[wire(name = …)]. There is no option to
set the policy. A Wado name that is reserved (lib:wadopoet's is_reserved)
takes a _ suffix, so the property in becomes the field in_. Its wire name
comes back under a policy, which drops the _, or else by
#[wire(name = "in")]. A name that leaves no word, that starts with a
digit, or that converts to the same Wado name as another in its scope is an
error.
A $ref resolves as C resolves it, so a declaration is a schema a reference
can name as a whole: a document's root, or an entry of its $defs. A reference
to any other subschema is an error. Another document's root and $defs entries
are declared only where a reference reaches them, under the root's title or
the file's name, and the entry's key. A root that is only a $ref is declared
only where the root option names it. A definition that admits null besides
a struct, enum or variant written in place is the Option of that type, which
is declared under the definition's name followed by Value.
A keyword the table does not read is an error naming its JSON Pointer,
$dynamicRef among them. An annotation is not, and neither is Core's $id,
$anchor or $defs: D reads description and default, and passes over the
rest. A type x-wado-format names takes no assertion beside type. An assertion keyword becomes a refined type
with the matching clauses, so B applied to D's output gives back the keywords D
read. Until refined types land, it is an error. D accepts
additionalProperties: false, since the type never writes another key, though
it decodes a document that has one, skipping the key.
No attribute of Jade's own
A package cannot own a compiler-recognized attribute, and Jade needs none. The
wire names come from #[wire(…)], which the decoder reads too. A permitted
range comes from a refined type. A description comes from a doc comment.
Progress
Status: Done. All four layers shipped as decided above, except what waits on
refined types and TypeInfo:
- [x] A: every Draft 2020-12 keyword and the boolean schemas, read from JSON
text through a
Documentand written back. - [x] B over the kind blankets, with the leaves for
core:temporal,core:uri,core:urlandcore:uuid, and the titles and descriptions doc comments give. - [x] C: the JSON Schema Test Suite's Draft 2020-12 cases pass, remote ones
included through
SchemaSetandValidator::compile_loading, and every format that needs no IDNA is asserted behindCompileOptions::assert_format. - [x] D: every shape in the mapping table is generated, B gives the schema back
from the output apart from the gaps kept in
package-jade/, and a consumer package imports a.schema.jsonthrough Kiln. An unboundedintegeris one such gap: it becomes ani64, and B writes thei64schema.
This WEP is complete and is not updated further. Jade's current design, its
user manual and its open work, the parts that wait on refined types and
TypeInfo included, are kept in package-jade/.
Related WEPs
- Refined Types — where a schema's assertion keywords come from
- Library-Defined Derivation over
Reflect*— the reflection B walks - Total Reflection —
TypeInfo, and thematch typethat would fold B's blankets - Serialization and Deserialization (Serde) — the decoder B mirrors
- Grog — the generator-and-runtime package D follows
- Kiln — the generator mechanism D uses
