Schema and autocomplete
jlens can learn the structure of your documents from samples and use it to help people write expressions. The language service then provides:
- completion of field names that knows which object you are in;
- warnings for fields that do not exist;
- hover documentation;
- signature help for functions.
The jlens-schema crate provides both parts, and the CLI and the WebAssembly package expose
them.
1. Infer a schema from samples
$ jlens schema infer samples/*.json -o order.schema.json
inferred from 120 sample(s): order.schema.json
Glob patterns are expanded by jlens itself, so they also work in Windows shells. With --each,
a sample file holding a top-level array counts as one sample per item.
Inference records, for every place in the documents:
| What | How |
|---|---|
| Types | Every JSON type seen. integer is used while all numbers are written without a fraction; 1500.0 makes it number |
| Fields | In first-seen order, with required when every object had the field, and the fraction of objects that had it otherwise |
| Array items | The merged shape of all items of all arrays seen at that place |
| Arrays never empty | minItems: 1 when no array seen at that place was empty |
| Numbers | Minimum and maximum |
| String formats | date-time, date, time, email, uuid or uri, when every string seen has that format |
| Enumerations | When the values come from a small set (at most 10) and repeat |
| Examples | Up to three distinct values |
The result is a standard JSON Schema 2020-12 document. JSON Schema
is a specification for describing the shape of JSON documents; new to it, start with its
step-by-step introduction or the
guide Understanding JSON Schema. Fields that are not required carry
x-jlens-presence, the fraction of objects that had them, and an inferred enum carries
x-jlens-enum-inferred: it lists the values seen, not every value allowed, so the language
service completes them but never warns about another one. Remove the keyword once the list is
complete, or set the values in the overrides (below). An inferred minItems carries
x-jlens-min-items-inferred: the language service takes it as it takes an inferred required
(the result’s type counts on it), so review both, and remove a
minItems where an empty array is allowed. You can commit the file, review it,
and edit it like any JSON Schema. jlens also reads JSON Schemas written by hand or by other
tools: it follows $ref, by JSON Pointer, $id and $anchor, merges the branches of allOf,
and reads those of anyOf and oneOf as one branch or another
(the keywords jlens reads lists the others).
A schema may be recursive: a tree whose children are {"$ref": "#"}, a definition that
refers to itself, definitions that refer to each other. Completion, hover and the diagnostics
follow it as deep as the expression goes, so that children.children.children.nane is warned
about as nane is. A $ref that leads nowhere but to itself says nothing of its place:
nothing is completed or warned about under it. In the Rust crate such a $ref is kept as a
reference to a definition of the schema
(ADR 0024): Schema::shape_at follows it, and
Schema::members gives the shapes that one stands for. A path of the overrides that goes
through it changes the definition, and so every place that refers to it: in that tree,
children[].label describes the label of every node.
A schema in several documents
A $ref may lead to another document ("$ref": "common.json#/$defs/person"). jlens never
fetches one: the application gives the documents, each with its URI, and the load reads only
those (ADR 0025).
#![allow(unused)]
fn main() {
use jlens_schema::SchemaLoader;
let (schema, report) = SchemaLoader::new()
.document("https://example.com/schemas/common.json", &common)
.load(&order)?;
for unresolved in &report.unresolved {
eprintln!("{}: {} was not followed", unresolved.place, unresolved.uri);
}
}
A $ref is resolved against the $id of the schema it is in, or the URI its document is given
with (load_at), and a document is known by that URI and by each $id in it. With neither, a
reference is taken as written: common.json#/$defs/person is a place of the document given as
common.json.
A $ref the load cannot follow does not fail it. Its place is left unknown, so that nothing
is completed or warned about under it, and the rest of the schema is checked as usual. The
report beside the schema lists each one: where it is written, what it resolves to, and the
document that was not given (report.documents() lists them, each once). What an expression
uses marks such a place unknown, so a document given later shows as a change. Only a
document that is not a schema, or one nested more than 64 levels deep, fails to load.
Schema::from_json_schema is that load with no other document and without the report.
Every package that reads a schema takes its documents and gives the report, in the same JSON
form ({"unresolved": [{"place", "reference", "uri", "document"}], "unread": [{"place", "keyword"}], "openTuples": [{"place"}]}, {} when every $ref was followed, every keyword
read and no tuple open; unread and openTuples are described
below):
| Where | The documents | The report |
|---|---|---|
| Rust | SchemaLoader::document, or load_asking with a function that gives them | LoadReport |
| WebAssembly | new LanguageService({ schema, sources: { uri, documents } }) | schemaReport(schema, { uri, documents }) |
| Java | Schema.loader().document(uri, text).load(text) | schema.unresolved(), schema.missingDocuments(), schema.unread(), schema.openTuples() |
| CLI and language server | the files beside the schema’s | a warning for each document not found and for each keyword not read, and one for the open tuples |
The CLI and the language server read a document from a file, and never from the network. The
file is the one at the same relative path from the schema’s file as between the two URIs:
beside schemas/order.json, "$ref": "common.json" is schemas/common.json and
"$ref": "../shared/money.json" is shared/money.json, whether the schema has an $id (the
path between https://example.com/schemas/order.json and
https://example.com/schemas/common.json is common.json) or not. A document on another
host, or one with no file there, is not read. A variable’s schema in jlens.json refers to
files from the folder of jlens.json. For each document that was not found, each $ref
to a place its document does not have, and each keyword not read, jlens check, jlens schema uses and
jlens schema complete print a warning: line on standard error, and one more that names the
open tuples, and the language server shows a message for each line; the exit code does not change, and --deny-warnings counts the warnings of
expressions only. A file that is there and is not JSON fails the command, as a schema that
is not JSON does.
In the Rust crate, SchemaLoader::load_asking is that loop: it asks a function for each
document the load misses, with its URI and its relative path from the schema, then for the
documents those refer to, each URI once and no more than 256.
What JSON Schema has no keyword for travels in jlens’s own x-jlens-* keywords, which other
tools ignore. jlens writes them and reads them back, so they can also be written by hand:
| Keyword | Meaning |
|---|---|
x-jlens-presence | On a field that is not required: the fraction of objects that had it, from 0 to 1 |
x-jlens-enum-inferred | The enum lists the values seen in the samples, not every value allowed: completion offers them, but a value outside them is not warned about |
x-jlens-min-items-inferred | The minItems comes from the samples: no array seen there was empty |
x-jlens-domain | An open domain: an identifier naming a list of values only the application can fetch |
x-jlens-hidden | true hides the field from completion, like hidden in the overrides (below); it is still known, so it is not reported as unknown, and hover shows it |
x-jlens-samples | At the root: the number of sample documents the schema was inferred from. For information only: nothing depends on it |
A field’s label is written as the standard title, and its description as description.
The keywords jlens reads
The diagnostics warn about what a schema does not allow: a field it does not list, a type it does not give. A keyword that allows more, left unread, would make them warn about what the schema allows; a keyword that only narrows what a place may hold cannot, and jlens leaves those out. So each keyword of JSON Schema (2020-12 and the drafts before it) and of OpenAPI 3.0 is read, left out because it only narrows, or reported. What each keyword means is in the JSON Schema reference.
| Keywords | |
|---|---|
| Read | type, properties, required, patternProperties, additionalProperties, unevaluatedProperties (as additionalProperties, where that is absent), items, prefixItems, additionalItems, unevaluatedItems, minItems, maxItems, enum, const, format, minimum, maximum, $ref, $id, $anchor, $defs, definitions, allOf, anyOf, oneOf, if with then and else, dependentSchemas, dependencies, nullable, title, description, examples, x-jlens-* |
| Left out: they only narrow | not, minLength, maxLength, pattern, multipleOf, exclusiveMinimum, exclusiveMaximum, uniqueItems, contains, minContains, maxContains, minProperties, maxProperties, propertyNames, dependentRequired, contentEncoding, contentMediaType, contentSchema |
| Left out: they describe | default, deprecated, readOnly, writeOnly, $comment, $schema, $vocabulary, $dynamicAnchor, $recursiveAnchor, discriminator, xml, externalDocs, example |
| Reported | $dynamicRef and $recursiveRef, which the scope of a validation resolves; a type that names no JSON type, such as "int" |
How some are read:
allOf: every branch holds, so its branches are merged with the rest of the schema: a field that one branch requires is always there, even where another branch lists it and does not require it. So do a$refand the keywords beside it.requiredholds wherever it is written: besideproperties, in a branch ofallOfor beside a$refwhose other parts list the field, or with nopropertiesat all. A field it names that nothing lists is a field whose shape is not known, so"required": ["id"]makesida field that is always there; an object that lists no field otherwise still has any other. In the branches ofanyOfandoneOf, a field is required only where every branch requires it.anyOfandoneOf: a value has the shape of one branch or another. It may have the types of any branch, and a field is required only where every branch requires it: withanyOfof a person with anameand a company with atax,namemay be absent, and a result that needs it getsW0214. A field that several branches declare has the types of any of them, and anenumor aconstlists the values of every branch, where each lists them (a branch ofnullalone listsnull). A branch that gives no type, such as{}or{"minLength": 1}, leaves the type unknown, as any value may match it, but for one withconstorenum, whose type is that of its values; atypebeside theanyOfstill holds.oneOfis read asanyOf: that only one branch matches only narrows.thenandelse, read only besideif, and the schemas ofdependentSchemasand of draft-07’sdependencieshold for some of the values only. The fields they declare, at any depth, are fields the object may have, none required; a field thatthenmakes a string andelsea number is either. What else they say only narrows, and is left out.- A tuple,
prefixItemsor draft-07’sitemsas an array, has its items merged with those of the rest (itemsafterprefixItems,additionalItems,unevaluatedItems), as a step over the array takes them all. With no schema for the rest, any item may follow, and the items are not known, unlessmaxItemskeeps the array to the tuple or the rest isfalse; the schema keeps that bound, and writes such a tuple back with"items": false. A literal index inside the tuple has the type of its position, whether items may follow or not: withpointa tuple of two numbers,point[1]is a number andpoint[1] > "a"getsW0208, and afterentry[1].completion offers the fields of the second item. An index from the end, one past the tuple or a computed one (point[-1],point[2],point[$i]) has the type of every item. An override atpoint[]sets each position as well. enumandconstwith notypegive the types of their values, as every value is one of them:{"enum": ["open", "closed"]}is a string, and{"enum": [1, "a", null]}a number, a string ornull. Atype, or one that a$refor a branch ofallOfgives, holds as written.nullable: trueaddsnullto the types a schema gives, and to itsenum.
A reported keyword leaves the place of its schema unknown, as a $ref that was not followed
does: nothing is completed or warned about under it. The report beside the schema lists each
one under unread, with place, the schema that has it (#/properties/children/items), and
keyword. The CLI and the language server warn about each, as they do about a document not
found.
A tuple with no schema for the rest and no maxItems that keeps the array to it is read, and
its positions are typed, but it may say less than its author meant: JSON Schema allows any item
after it, so point.($ > "a") and point[2] are not checked for a point meant as two
numbers. The report lists each one under openTuples, with its place (#/properties/point),
and the CLI and the language server name them in one warning. "items": false after
prefixItems, "additionalItems": false in draft-07, or maxItems closes the tuple; true
in place of false says that it is open on purpose, and it is no longer listed. Nor is a tuple
whose schema knows its items by a $ref or a branch of allOf.
Left out, a narrowing keyword can still leave the typing less sure than the schema is: with
not: {"type": "null"}, a field may still be null to it, and a field that then requires
may still be absent.
2. Describe the fields
Samples tell jlens what fields exist, but not what they mean. Overrides add that information.
An overrides file maps paths to settings; [] steps into array items:
{
"items[].type": {
"description": "Product category used for catalog classification",
"enum": ["apparel", "electronic", "toy"]
},
"items[].tax": { "label": "Import tax" },
"customer.login": { "description": "Login chosen at sign-up" },
"internalRevision": { "hidden": true }
}
| Setting | Effect |
|---|---|
description | Shown in completion and hover |
label | A display name, shown in bold |
enum | The allowed values |
domain | An open domain: values the application provides (see Open domains) |
examples | Example values |
format | A format name |
type | Replaces the inferred types: one name such as "integer", or a list such as ["string", "null"], as in JSON Schema. The names are JSON Schema’s: null, boolean, integer (a number without a fraction), number, string, array and object |
hidden | Never suggested by completion |
$ jlens schema infer samples/*.json --overrides overrides.json -o order.schema.json
A path that does not exist yet is created, so overrides can also declare fields that are absent
from the samples. A misspelt path does the same, so jlens schema infer warns about each such
path, naming the existing path it most likely meant:
warning: override path items.type is not in the samples; declared (did you mean items[].type?)
In Rust, Schema::missing_override_paths lists them before apply_overrides creates them
(missingOverridePaths in the Wasm package).
3. Use it
In the terminal
$ jlens check --schema order.schema.json -f rule.jsonata
warning[W0201]: Field "unitprice" is not in the schema; did you mean `unitPrice`?
--> rule.jsonata:4:22
|
4 | $sum(items[type = 'x'].unitprice)
| ^^^^^^^^^
$ jlens schema complete --schema order.schema.json "items[type = 'electronic']."
code field string
color field string
type field string
unitPrice field number
quantity field integer
tax field number
--cursor N sets the cursor position in characters, and --json prints the full completion
items.
In Rust
#![allow(unused)]
fn main() {
use jlens_schema::{FunctionDecl, LanguageService, Schema};
let schema = Schema::from_json_schema(&serde_json::from_str(&schema_text)?)?;
let service = LanguageService::new(Some(schema))
.with_variable("approved", None) // variables the rule is evaluated with
.with_function( // and its host functions
FunctionDecl::new("shipping", "Shipping cost of a weight to a region")
.signature("<ns?:n>")
.params(["weight", "region"]),
);
let completions = service.complete(text, cursor_byte_offset);
let diagnostics = service.diagnostics(text);
let hover = service.hover(text, cursor_byte_offset);
let help = service.signature_help(text, cursor_byte_offset);
}
Declare the host functions the expressions are evaluated with: they are completed first, and hover and signature help show their signature, parameters and summary. A declared function replaces a built-in function of the same name, as it does during evaluation.
All offsets and spans in the Rust API are byte offsets into the expression text. The
WebAssembly package converts them to and from the UTF-16 offsets that browsers and editors use;
an application that builds the service into a module of its own converts them with
jlens_core::Offsets.
In the browser
The WebAssembly package exposes the same service for editors such as CodeMirror and Monaco; see the WebAssembly guide.
What completion understands
Completion knows the context at the cursor, that is, which object the next field name will be looked up in. It follows the evaluator’s rules:
| You type | Suggested |
|---|---|
items. or items[...]. | Fields of an item (arrays are flattened, as during evaluation) |
items[ … ] | Inside the predicate: fields of an item |
items{ … } / items^( … ) | Fields of an item, in group-by keys and values and in sort keys |
$sum(items.( … )) | Fields of an item, inside a block applied to each item |
($i := items[0]; $i. | Variables keep the type of what was assigned to them |
items@$it. … $it. | Focus variables bind the items of their step |
$map(items, function($i){ $i. | Callback parameters of $map, $filter, $single, $sort and $reduce get the item type |
$sort(items, …)[0]. | Functions that return their input ($sort, $filter, $reverse, …) keep its type |
items.%., items[%. … ], items.code.%. | The parent: fields of the object the step that % refers to is evaluated against, the order for an item of items |
items.`ty | Field names that need backquotes |
$su | Variables in scope, then declared host functions, then built-in functions |
customer.login (after a space) | Operators: and, or, in |
type = , type != , type in [, type in ["toy", | The values of type’s enumeration first, then fields, variables and functions |
type = "ap | The string values of type’s enumeration that start with ap |
Each field suggestion carries:
- its type (
string,array<object>,integer | null, …); - its label and description;
- its presence, for optional fields;
- its allowed values or examples.
Field names that are not plain identifiers are inserted with backquotes, and hidden fields are never suggested.
Values (kind value) come from the enumeration of the left-hand side of =, != or in: a
schema’s enum or const, one set in the overrides, or one inferred from samples. examples
are not offered, as they are not every value. A value is inserted as a JSONata literal, a string
quoted and escaped. Inside quotes the whole literal is replaced, and the string keeps single
quotes when it can (JSONata has no \' escape). In an array after in, the values already
listed are left out.
Open domains
An enum is a closed list, written with the schema. Some fields take their values from a list
only the application can fetch, often a large one, such as customers or products. Such a field
names its domain, an identifier only the application understands: x-jlens-domain in the
JSON Schema, or domain in the overrides:
{ "customer.login": { "domain": "customers" } }
At the positions where values are completed, the completions then carry, beside their items, a
value request (Completions::value_request): the domain, the field’s path in the schema
(customer.login; none for a variable), the prefix typed so far, the range a value replaces and
the quote it is written with. The service stays synchronous: the application fetches the values
that match the prefix, caches them as it sees fit, and writes each as a JSONata literal with
ValueRequest::literal (valueLiteral in the Wasm package). Values the field also declares in an
enum are still completed as items. A value outside an open domain is never warned about, and
hover names the domain.
The values of one domain often depend on another value: the subgroups of a group, the states
of a country. The request carries the fields already fixed beside the value, its conditions:
each field compared with a literal by =, or with an array of literals by in, that is joined
to the value’s comparison by and, in the same predicate or, outside any, in the whole
expression. In items[categories[group = 'Electronics' and subgroup = '|, the request for
subgroup has the condition items[].categories[].group = ["Electronics"], read from the
expression as it is typed, unfinished. A comparison on one side of or, by !=, with something
that is not a literal, inside a call such as $not(...) or in another predicate is not a
condition. The request also says whether the value is an element of the array of in [...]
(in_array), where the application may insert several values, separated by commas, and which
literals that array already holds (listed), so that the application does not offer them again,
as the service does not complete a declared value twice.
Completion works on incomplete expressions too, such as $count(items[ or
items[type = 'x' and . That is the normal state of an expression while someone types it.
Diagnostics
LanguageService::diagnostics returns:
- syntax errors, from the recovering parser;
- annotation warnings;
W0201warnings for field names the schema does not have, with a “did you mean” suggestion when a field name is close. Under the parent operator,items.%.custmer, the field is looked up in the parent; where the typing does not tell the parent, as for a step inside parentheses (customer.(login).%), nothing is reported;W0202warnings for calls of unknown functions, with the same kind of suggestion, andW0203warnings for calls with too few or too many arguments for the function’s signature. These need no schema. A function is known when it is built in, declared withLanguageService::with_function(or injlens.json), or bound anywhere in the expression; a variable declared withwith_variablemay hold a function, so its calls are not checked;W0205warnings for arguments whose type the function’s signature cannot accept, such as$sum(items.name)whennameis a string. Only types that are known count: literals, the results of operators, and fields of the schema. A field that is absent passes any signature; the warning means that the call fails whenever the field is present;W0204warnings for variables that are not declared, with a suggestion, when at least one variable is declared withwith_variable(or injlens.json): the declarations are then taken to be complete. Names bound in the expression, and functions, are known;W0206warnings for a literal compared with a field, by=,!=orin, that is not one of the field’s declared values, such asitems[type = "aparel"]: the comparison is always false. A string gets the nearest value as a suggestion (did you mean "apparel"?). Only anenumorconstof the JSON Schema, or anenumset in the overrides, counts: one inferred from samples (x-jlens-enum-inferred) is a guess, and is never warned about, and neither is a field with an open domain. Values that are not literals, such astype = color, are not checked;- warnings for the operands of an operator whose types it cannot take, so that the expression
fails whenever they are present, or a comparison is always false. With
totala string,total > 1000getsW0208: strings and numbers are not compared with each other (T2009when it runs). A side of<,<=,>or>=that is a boolean, null, an object or an array of them has no order,W0207(T2010), and a side of+,-,*,/or%that is not a number getsW0209(T2001,T2002), as does the operand of a negation,-x, withW0211(D1002). Withactivea string,active = truegetsW0210: a field compared by=,!=orinwith a literal of another type is never equal to it. A field with a declared enumeration getsW0206there instead, and two literals compared are left alone. As forW0205, only types that are known count, an absent field passes, and an array stands for its items:scores > 1gets none of these whenscoresis an array of numbers, butW0215, below; W0215for an operand that may be several values. A path over several items gives a sequence:items.qty > 1is true for an order of one item and fails for two (T2010),items.qty + 1fails too (T2001), anditems.qty = 2is false for two, as=compares the array. A field that holds an array is an array even of one item:tags > 'a'fails, andtags = 'a'is false. The warning names the step that makes the sequence (the step over an array, a filter that may keep several items,*,**,$keys) and says what to write instead: an aggregate,$max(items.qty) > 1or$sum(items.qty) + 1; a filter that tests each item,$count(items[qty > 1]) > 0;into find a value among them,2 in items.qty. A number filter keeps one item, soitems[0].qty > 1gets nothing, nor does a filter of an object,order[qty > 1].=and!=are warned about only where the other side is one value. The text tells the two cases apart: an operand that is always an array, such astags, “is an array, which never equals one value”, sotags = 'a'is false for every document that follows the schema; one that is an array only for some documents, such asitems.qty, “may be several values”, and passes a test with one item. For=and!=the hint writes the expression again, with the other side looked for in the array:'a' in tagsfortags = 'a', and$not('a' in tags)fortags != 'a'. As!=is false where a side is undefined and$not(… in …)true, that form starts with$existsof each side that may be undefined:items.qty != 2gives$exists(items.qty) and $not(2 in items.qty). The rewrite gives the same answer wherever the operand is one value or undefined, and changes it only where it is several values;- with the type the result must have declared,
W0212,W0213andW0214for a result that never has it, may have another, or may be undefined (below).
The typing does not read the guards of an expression: in $type(x) = 'number' and x > 10, with
x a string in the schema, x > 10 is warned about, though the left side, always false, keeps it
from running.
An expression that is the body of a step
An application may evaluate an expression against each item of an array, as the body of
items.( … ): a rule on each line of an order. Declare the path of the items, and the service
completes and checks the text with an item as its context, at the offsets of the text, without
the application wrapping it:
#![allow(unused)]
fn main() {
let service = LanguageService::new(Some(schema)).with_context_path("items[]");
let diagnostics = service.diagnostics("price > 10 and %.customer.vip");
}
% is then the value the last step of the path was evaluated against, the order, where alone
it fails with S0217; %.% is the one before, for a path of two steps such as
orders[].items[]. $$ stays the document. The path is written as for Schema::shape_at;
items and items[] are the same context, as a step reads the items of an array. A path the
schema does not have gives an unknown context, where no field is warned about. In an editor and
in jlens check, the contextPath of jlens.json declares
it, or jlens check --context-path 'items[]'; in the WebAssembly
and Java packages, the service’s options.
Missing fields are reported only where the context is fully known. Nothing is reported after a
user-defined function, an object constructor or $lookup, so the warnings do not produce false
alarms. Schemas inferred from samples can miss optional fields that the samples did not contain.
Add those fields with overrides, or treat W0201 as advice.
Objects open to other fields
JSON Schema lets an object have fields its properties do not list, unless
additionalProperties is false. jlens takes an object that lists its fields in properties
to have those alone, and warns about another one: it is most often a typo, and the warning is
what the schema is there for. An object that says it has others is not warned about: one with
additionalProperties other than false (true or a schema), with patternProperties, or
with no field listed at all, such as {"type": "object"}, often a map whose keys are data. An
object always empty in the samples a schema is inferred from lists no field either.
additionalProperties gives such a field its type, and each pattern of patternProperties the
fields whose names it matches (an ECMAScript regular expression, which may match anywhere in the
name). With "additionalProperties": {"type": "number"} on totals, totals.usd + 1 gets
nothing and totals.usd > 'a' gets W0208. A field the object does not list may be absent,
which counts for the result’s type. Patterns alone leave the other
fields unknown; with "additionalProperties": false beside them, a name no pattern matches is
warned about. A name that several patterns match, or that a pattern takes too long to match, has
a type that is not known, and so has a field of {"type": "object"}.
The type of the result
An application often knows the type an expression must give: the conditions of a rules engine must give a boolean. Declare it, and the diagnostics compare the result with it:
#![allow(unused)]
fn main() {
use jlens_schema::{JsonType, LanguageService};
let service = LanguageService::new(Some(schema)).with_result_type([JsonType::Boolean]);
let diagnostics = service.diagnostics("$contains(notes, 'urgent')");
// W0214: The result may be undefined, not a boolean, because of notes
}
There are three answers. The result is always one of the types, and nothing is reported. It
is never one of them, W0212, as total is a number. Or it may not be: W0213 when it may
have another type, with the types it may have, and W0214 when it may be undefined, pointing
at the operand that makes it so. Number accepts an integer.
Most conditions are proved without a document: =, !=, in, and, or and $exists
always give a boolean. An order comparison, arithmetic and most functions are undefined
where an operand is, and these may be undefined:
- a field that is not required, and what is under it:
$contains(notes, 'urgent'); - a filter, which may keep nothing:
items[type = 'gift'].price > 10; - a step over an array that may be empty, as
$sum(items.price) > 100is whenitemsis[]($sumof nothing is undefined). An array withminItemsof at least 1 is never empty, and inference givesminItems: 1to an array no sample had empty; - a function that may give nothing, such as
$lookup,$maxof an empty array or$keysof an object without fields, and a condition withoutelse.
A path over several items gives a sequence: one value alone, or several in an array.
lines.price is a number for an order of one line and an array for an order of two, so a
result expected to be a number gets W0213, pointing at lines; $sum(lines.price) is one
number. An array constructor, [price], and functions such as $sort always give an array.
Where the typing does not know the type, nothing is reported: a function the expression
defines, an object constructor, a path that binds @$v or #$i, a variable declared without a
shape, a field without a schema, the parent of a step inside parentheses. LanguageService::result_type gives what it knows as a value,
with no expected type: the types the result may have (None where they are not known) and the
spans of the operands that may make it undefined or a sequence. ResultType::check compares
it with a list of types, and answers Always, Never, Maybe or Unknown.
In an editor and in jlens check, the resultType of
jlens.json declares the type for the files of a pattern, as "resultType": "boolean", or
jlens check --result-type boolean; the WebAssembly
and Java packages take it when a service is
made, and their resultType gives the result’s type in this JSON form, with UTF-16 spans.
jlens schema result prints the result’s type as JSON, with check where a type is expected:
$ jlens schema result --schema order.schema.json --result-type boolean '$contains(customer.name, "VIP")'
{
"types": [
"boolean"
],
"undefined": {
"start": 10,
"end": 18
},
"sequence": null,
"check": "maybe"
}
An expression with a syntax error has no answer from the command: it prints the error on
standard error and ends with exit code 1, as jlens check and jlens schema uses do. The
resultType of the packages does not fail: its types are not known, and the service’s
diagnostics have the error.
What an expression uses of its schema
An application may store expressions written against a schema that changes. When a new version
of the schema arrives, the diagnostics tell whether each expression still passes: a field that
went from a boolean to a string gets W0210 under active = true. They do not tell whether
something it uses changed while the expression stays valid: an enumeration that gained held
leaves status = 'open' passing, and the expression may need a case for it.
LanguageService::uses answers that. It takes the fields an expression
reads and gives what the schema says of each:
#![allow(unused)]
fn main() {
use jlens_core::Expression;
use jlens_schema::{LanguageService, Schema};
let service = LanguageService::new(Some(schema));
let expression = Expression::compile(r#"$sum(items[type = "book"].price)"#)?;
let uses = service.uses(&expression.reads());
let json = serde_json::to_string(&uses)?; // kept beside the expression
}
{
"input": {
"$": {"types": ["object"]},
"items": {"types": ["array"], "required": true},
"items[]": {"types": ["object"]},
"items[].price": {"whole": true, "types": ["number"], "required": false},
"items[].type": {"whole": true, "types": ["string"], "enum": ["book", "toy"],
"closed": true, "required": true}
},
"bindings": {}
}
input holds the paths read of the input, and bindings those of each variable, by name;
input is left out when the expression does not read its input. A path is written as the
overrides write it: $ is the value itself, [] steps into the items of an array, and a name
that is not a plain one is written between backquotes, as in an expression (customer.`odd name` ). Schema::shape_at reads every path of an answer, but a name that itself holds a
backquote. Every value on the way to a field has its own path, and so do the items of an array.
What the schema says of a path:
| Member | Meaning |
|---|---|
types | The types the schema gives the value, as JSON Schema names them; left out when it gives none |
enum | The values it lists |
closed | true when the enumeration is declared and has no open domain, so that a value outside it is warned about (W0206); left out for one inferred from samples |
domain | Its open domain |
format | Its string format |
required | Whether the object that holds the field requires it. Left out for $ and for the items of an array. A field is always there only when the fields on its way are required too |
whole | true when the expression reads the value whole, not only some of its fields |
unknown | true when the schema says nothing there: the value has no schema, or the field is not one it declares |
The paths are those of the analysis of the reads, which is an upper bound. Where it follows a
value, they are the fields the expression names, those of a predicate included. Where it does
not (*, **, $eval, a value given to a host function), the value is read whole, and every
path the schema has under it is listed. $eval can also read any variable: the answer then has
"everyBinding": true, and every variable declared with a schema, whole. The host functions
declared to the service are not values, and are left out of bindings.
The call of a function that is not built in reads the context of its call whole, as a host
function written in Rust can read it: $describe(items[0]) at the top of an expression uses the
whole input, and every change of the schema is then a change for the expression. The host
functions of the WebAssembly, Python and Java packages receive their arguments and nothing
else, and so do those marked HostFunction::without_input in Rust. LanguageService::uses_of
takes the expression itself, and counts a call to a function declared to the service
(with_function) as reading its arguments alone, and the context that a - of its signature
may take: the call above uses items, whole, and nothing else.
#![allow(unused)]
fn main() {
let uses = service.uses_of(&expression);
}
Give uses the reads when a declared function reads its context, or when the application
knows better which functions do (Expression::reads_with).
Under a value read whole, a recursive schema is listed down to where it repeats: what is
under a definition is listed once, at the place nearest to the value read whole, and another
value of that definition is the last path on its way. Read whole, a tree whose children are
the document itself gives $, its fields, children and children[]. A change inside the
definition shows in the paths listed.
The answer depends on nothing else in the schema, and its paths and names are written in order: two schemas that give an expression the same text differ in nothing it uses.
What changed between two schemas
When the answers differ, Uses::changes tells where. It compares the answer kept beside the
expression with that of the new schema:
#![allow(unused)]
fn main() {
let old: Uses = serde_json::from_str(&kept)?;
let new = LanguageService::new(Some(new_schema)).uses(&expression.reads());
let changes = old.changes(&new);
if !changes.is_empty() {
let json = serde_json::to_string(&changes)?; // shown to who reviews the expression
}
}
With price now an integer or a string, type no longer required and with one more value, and
a field weight added to the items, an expression that reads the items whole
(items[type = "book"]) gets:
{
"input": {
"added": {
"items[].weight": {"types": ["number"], "required": false}
},
"changed": {
"items[].price": {"types": {"old": ["number"], "new": ["integer", "string"]}},
"items[].type": {
"enum": {"old": ["book", "toy"], "new": ["book", "game", "toy"], "added": ["game"]},
"required": {"old": true, "new": false}
}
}
}
}
input and bindings, by variable, hold the changes as the answers hold the paths, and each is
left out when nothing changed there: {} means that nothing the expression uses changed.
| Member | Meaning |
|---|---|
added | The paths that only the new answer has, with what the new schema says of each: a field added under a value the expression reads whole |
removed | The paths that only the old answer has, with what the old schema said: a field removed under a value read whole |
changed | The paths of both answers of which the schemas do not say the same. Each has the members that changed, under their names in the answer, as {"old": …, "new": …}; a side on which the member was left out is left out here too |
A field that the expression names stays in the answer when the new schema drops it. It is then
under changed, with "unknown": {"old": false, "new": true} and what the old schema said of
it. A path is compared with the same path, so a field that was renamed is one path that became
unknown, or was removed, and another that was added.
The types and the values of an enumeration are compared as sets: their order is not a change.
An enumeration that changed also has added and removed, the values that only one side
lists, so that an application can tell a value that was added, which leaves the expression’s
comparisons as they were, from one that was removed.
In the CLI and the other packages
Every place that has the schema gives the two answers, as the same JSON:
| Where | What an expression uses | What changed |
|---|---|---|
| Rust | LanguageService::uses(&reads), uses_of(&expression) | Uses::changes(&new) |
| CLI | jlens schema uses <EXPR> | jlens schema changes OLD NEW |
| WebAssembly | service.uses(expression.reads(bindings)) | usesChanges(old, current) |
| Java | service.uses(expression) | uses.changes(current) |
The comparison takes the two answers and nothing else, so the answer kept beside an expression
is compared when its schema is gone. In Rust, Uses::from_json reads an answer kept as JSON; it
refuses what is not in the form above, where the derived Deserialize would take an array for
an object.
jlens schema uses prints the answer of an expression, given as an argument or with -f. It
takes its schema, variables and host functions as jlens check does:
from --schema, and from the jlens.json of the current directory or of --config, which
--path applies to an expression given as an argument. A host function the configuration
declares reads its arguments alone, as uses_of takes it. jlens schema changes compares two
files it wrote:
jlens schema uses -f rules/books.jsonata --schema order-v1.schema.json > books.uses.json
jlens schema uses -f rules/books.jsonata --schema order-v2.schema.json > books.new.json
jlens schema changes books.uses.json books.new.json
input
added items[].weight: number, optional
changed items[].price: types number -> integer | string
changed items[].type: enum added "game"; required true -> false
It prints no change when nothing the expression uses changed, and with --json the JSON form,
{} then. Both commands exit with 0 whether something changed or not; a file that is not an
answer is a usage problem, 2.
The fields of a schema
An application that builds its own list of attributes from a schema, as a rules editor does for
its menus, or that matches the fields of two versions of a schema to see which moved, needs each
field with what jlens knows of it. Schema::fields lists them, so that the application does not
walk the schema itself, through its $refs, branches and tuples:
#![allow(unused)]
fn main() {
use jlens_schema::Schema;
let schema = Schema::from_json_schema(&serde_json::json!({
"type": "object",
"required": ["status"],
"properties": {
"status": {"type": "string", "title": "Status", "enum": ["open", "closed"],
"x-attribute-id": "A17"},
"lines": {"type": "array", "items": {"type": "object", "properties": {
"sku": {"type": "string", "x-jlens-domain": "products"}}}},
"internal": {"type": "string", "x-jlens-hidden": true}
}
}))?;
let fields = schema.fields();
}
[
{"path": "$", "typeSummary": "object", "types": ["object"]},
{"path": "lines", "typeSummary": "array<object>", "types": ["array"], "required": false},
{"path": "lines[]", "typeSummary": "object", "types": ["object"]},
{"path": "lines[].sku", "typeSummary": "string", "types": ["string"], "required": false,
"domain": "products"},
{"path": "status", "typeSummary": "string", "types": ["string"], "required": true,
"label": "Status", "enum": ["open", "closed"], "closed": true,
"extensions": {"x-attribute-id": "A17"}}
]
Each entry tells what completion and hover tell of its path:
path, written as the answers ofuseswrite it, and in their order:$is the value itself,[]the items of an array. A recursive schema is listed down to where it repeats, asuseslists a value read whole.typeSummary, the types as completion shows them, andtypes, as JSON Schema names them;unknownand no types where the schema says nothing, as under a$refthat was not followed.required, for a field only, wherever the schema says it (the keywords jlens reads);label(title) anddescription;enum, withclosedwhen a value outside it is warned about;domainandformat.extensions: the field’s ownx-keywords, as written, which jlens keeps and does not read, such as a key that the application gives each field and that stays the same when the field is renamed. Those of a$ref’s place come before those of its target. A schema written back byto_json_schemakeeps them.
The overrides applied to the schema are in the list, and a hidden field is left out with what is
under it, as completion leaves it out. LanguageService::fields lists the fields of the schema of
the service’s input; the WebAssembly and
Java packages call it service.fields(), with the same JSON.
Fields renamed by a new version
When a new version of a schema renames fields, the expressions written against the old one still
name the old fields. LanguageService::rename rewrites them: given a table of paths, each old
path to its new one, it replaces each step that reads a renamed field, found as uses finds the
fields an expression reads, and keeps the rest of the text as written. A rule migrated to a new
version takes four steps: what changed, the table, the rename and the check.
#![allow(unused)]
fn main() {
use std::collections::{BTreeMap, HashMap};
use jlens_core::Expression;
use jlens_schema::{LanguageService, ListedField};
// Two versions of the schema of an order, each field with a key of the application's:
// `lines` became `items`, and `qty` `quantity`.
let before = LanguageService::new(Some(version_1));
let after = LanguageService::new(Some(version_2));
let rule = Expression::compile("status = 'open' and $sum(lines.(qty * price)) > 100")?;
// 1. Does the rule use anything the new version changed? `lines` and `qty` are gone.
let changes = before.uses_of(&rule).changes(&after.uses_of(&rule));
assert!(changes.input.removed.contains_key("lines[].qty"));
// 2. The table: each old path to the new one with the same key.
let key = |field: &ListedField| field.extensions.get("x-attribute-id").cloned();
let new_paths: HashMap<_, _> = after.fields().into_iter()
.filter_map(|field| Some((key(&field)?.to_string(), field.path)))
.collect();
let table: BTreeMap<String, String> = before.fields().into_iter()
.filter_map(|field| Some((field.path.clone(), new_paths.get(&key(&field)?.to_string())?.clone())))
.collect();
// 3. The rename.
let renamed = before.rename(&rule, &table)?;
assert_eq!(renamed.text, "status = 'open' and $sum(items.(quantity * price)) > 100");
assert!(renamed.unsure.is_empty());
// 4. The rewritten rule uses nothing the new version does not have.
let migrated = Expression::compile(&renamed.text)?;
assert!(after.uses_of(&migrated).input.iter().flatten().all(|(_, used)| !used.unknown));
}
A step is renamed where it reads the field, whatever the path that leads there: a relative path
in a predicate, a parent kept in a variable ($o := order; $o.total), the parent of %, a step
written as a string (customer."name"). The same name under another parent, or of an object the
expression builds, is left alone. A new name that is not a plain one is written between
backquotes, and so is one the text beside it would run into (`a`and b with a renamed x
gives `x`and b). An entry renames the last name of its path. A field under a renamed parent
follows it without an entry of its own, and an entry for it gives it under the new parent
(lines[].qty to items[].quantity), as a table built from the two versions’ fields does; an
entry that moves a field to another parent fails, and so do a field renamed twice, two fields
renamed to the same path, a path with a backquote that opens or closes no name or a dot with no
name before it (a..b), and a name that holds a backquote, which JSONata cannot write.
The answer gives the rewritten text, each edit with its span, and the places the rename cannot
be sure of, in unsure, where it leaves the text as written for someone to look at:
reason | The place |
|---|---|
whole | A value that holds a renamed field is used whole: given to a function that may read the field or its name ($keys(customer), $sift, $string, a function of the expression’s own or a host function the service does not declare), iterated by * or **, an operand. path is the value |
string | A renamed field named by a string given to $lookup, as in $lookup(customer, 'vip') |
mixed | A step that reads a renamed field and another one, which keeps its name: (x ? a : b).name with a.name renamed alone, or (x ? a : $sift(b, $f)).name, where the other is a field of an object the expression builds or a function gives (a group-by, $spread, a function of the expression’s) |
lost | The analysis gave up on part of the expression, as for $eval: a renamed field may be read anywhere |
The result of the expression is not listed: an expression that returns an object holding a
renamed field returns it with its new name. Only the fields of the input are renamed, not those
of variables. The WebAssembly and
Java packages call it service.rename(...), with the
spans in UTF-16 code units.