Writes the JSON Schema (draft 2020-12) that the documents of a type
satisfy, for tools outside R8: each named type it reaches is in $defs,
and the root admits the document envelope. R8's facts that JSON Schema
cannot state, such as rules and units, are annotations under x-r8.
Arguments
- x
An R8 type object, or a typed function of
new_function().- closed
Logical: Write each
dyn()field as the closed list of the implementors registered in the session, each with its tag value as a constant, and eachsubtype()field as the struct and its registered descendants, each with"$type"as a constant, in place of an object that names its type. The annotationx-r8.closedis then"registered".
Details
For a typed function of new_function(), the schema is that of the
arguments object of a document of a call (r8call_from_json()), which a
tool's input schema takes: one property per parameter, with its
description, and additionalProperties: false. A parameter without a
default is required, and one of type option() admits null. A default
written as a constant is default; a default written in R is optional,
annotated x-r8.host_default with its text, which the function evaluates
when it runs. The function's name, rules, and return type are annotations
under x-r8. A function with a parameter without a type, ..., or a
parameter of type host_class() has no schema, and raises
r8_type_error, which names them.
Examples
op <- options(r8.namespace = "demo")
Point <- new_struct("Point", fields = list(x = type_double(), y = type_double()))
cat(r8schema(Point))#> {
#> "type": "object",
#> "properties": {
#> "x": {
#> "type": "number"
#> },
#> "y": {
#> "type": "number"
#> },
#> "$type": {
#> "type": "string"
#> },
#> "$types": {
#> "type": "object",
#> "additionalProperties": {
#> "type": "integer",
#> "minimum": 1
#> }
#> },
#> "$declarations": {
#> "type": "object",
#> "additionalProperties": {
#> "type": "string",
#> "pattern": "^sha256:[0-9a-f]{64}$"
#> }
#> },
#> "$ir": {
#> "type": "array",
#> "items": {
#> "type": "object"
#> }
#> }
#> },
#> "additionalProperties": false,
#> "required": [
#> "x",
#> "y"
#> ],
#> "$schema": "https://json-schema.org/draft/2020-12/schema",
#> "title": "demo::Point"
#> }clip <- new_function(
"clip",
function(
x = arg_vec(type_double(), description = "The values."),
lo = arg_double(default = 0, description = "The lower bound.")
) {
pmax(x, lo)
}
)
cat(r8schema(clip))#> {
#> "$schema": "https://json-schema.org/draft/2020-12/schema",
#> "title": "demo::clip",
#> "type": "object",
#> "properties": {
#> "x": {
#> "type": "array",
#> "items": {
#> "type": "number"
#> },
#> "description": "The values."
#> },
#> "lo": {
#> "type": "number",
#> "description": "The lower bound.",
#> "default": 0
#> }
#> },
#> "required": [
#> "x"
#> ],
#> "additionalProperties": false,
#> "x-r8": {
#> "function": "demo::clip"
#> }
#> }options(op)