From e6a1c74a34c821355680e103708e5707a4709208 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:02:20 +0000 Subject: [PATCH] Option for minimal types, with the validation in a separate file - `generate_module(...; validation = :separate)`: the constructors of the generated types only convert values to the types of their fields, and the checks of the constraints (the constraints of each type, the subschemas checked at runtime and the validator) go in a separate file, `validation.jl` (or `_validation.jl`), that the module includes only if it is present. It provides `validate`, `violations`, `isvalid` and `check_formats!`, and makes `tojson`/`writejson` validate first. - `validation = :none`: minimal types, without the validation file. - `validation = :inline` (the default) is as before. - The runtime is split into `runtime.jl` (reading and writing) and `runtime_validation.jl` (the checks). - The conformance harness takes `--validation=separate`. - Docs, README, tests and an example (`AcmeNestedMinimal`). Co-Authored-By: Claude Opus 5.5 --- README.md | 31 + docs/src/api.md | 4 +- docs/src/guide.md | 27 + examples/generate_examples.jl | 4 + examples/generated/AcmeFlat.jl | 674 +++++++------- examples/generated/AcmeNested.jl | 674 +++++++------- examples/generated/AcmeNestedMinimal.jl | 648 +++++++++++++ .../generated/AcmeNestedMinimal_validation.jl | 852 ++++++++++++++++++ examples/generated/AcmeNestedMod.jl | 674 +++++++------- examples/generated/AcmeWithReference.jl | 674 +++++++------- .../generated/BeerJSONTypes/BeerJSONTypes.jl | 8 +- examples/generated/BeerJSONTypes/runtime.jl | 836 +---------------- .../BeerJSONTypes/runtime_validation.jl | 815 +++++++++++++++++ examples/generated/Combined.jl | 674 +++++++------- examples/generated/Enum.jl | 674 +++++++------- examples/generated/Order.jl | 674 +++++++------- src/generator.jl | 142 ++- src/runtime.jl | 836 +---------------- src/runtime_validation.jl | 812 +++++++++++++++++ test/json-schema-test-suite/run.jl | 10 +- test/runtests.jl | 80 +- 21 files changed, 6007 insertions(+), 3816 deletions(-) create mode 100644 examples/generated/AcmeNestedMinimal.jl create mode 100644 examples/generated/AcmeNestedMinimal_validation.jl create mode 100644 examples/generated/BeerJSONTypes/runtime_validation.jl create mode 100644 src/runtime_validation.jl diff --git a/README.md b/README.md index eace619..20de49a 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,10 @@ The generated module exports: `nothing`. Defaults to `false`, since the defaults are then written out. * `checks`: whether the checks of the constraints are on when the module is loaded. Defaults to `true` (see [Turning the checks off](#turning-the-checks-off)). +* `validation`: `:inline` (the default), the constructors check the constraints of the + schema; `:separate`, minimal types whose constructors do not, with the checks in a + separate, optional file; `:none`, minimal types without any checks (see + [Minimal types](#minimal-types-with-the-validation-in-a-separate-file)). ### Splitting into several files @@ -186,6 +190,33 @@ violations(recipe2) # ["batch_size.unit: invalid value \"litre\" for `VolumeUn writejson("recipe.json", recipe2) # SchemaValidationError ``` +### Minimal types, with the validation in a separate file + +With `validation = :separate`, the generated types are minimal: the same structs, with the +same constructors, which convert the values to the types of their fields but do not check +the constraints of the schema. Everything needed to check them (the constraints of each +type, the subschemas checked at runtime and the validator) goes in a separate file, +`validation.jl` (or `_validation.jl` next to the module file, without `split`), which +the module includes only if it is present: + +```julia +isfile(joinpath(@__DIR__, "validation.jl")) && include("validation.jl") +``` + +Without that file, the module only reads and writes. With it, it also has `validate(x)`, +`violations(x)` and `isvalid(x)`, and `tojson` and `writejson` validate before writing +(unless given `validate = false`). Reading is not checked: use `validate(readjson(T, file))` +for that. With `validation = :none`, the validation file is not written at all. + +The types still enforce the structure of the schema: the types of the properties, required +properties, the properties allowed and the enumeration types. A JSON value read into a +union of generated types (from `oneOf` or `anyOf`) gets the first option that fits by its +properties and the values of its enumerations (e.g. a `unit` that is `"l"` for a volume, `"kg"` +for a mass); options that only differ by other constraints cannot be told apart. + +For BeerJSON, the minimal module is 221 KiB of code, instead of 280 KiB, and the +validation file 90 KiB. + ### Type names Type names come from the definition names, for example `#/definitions/VolumeType` becomes diff --git a/docs/src/api.md b/docs/src/api.md index 3b3b79e..fe20267 100644 --- a/docs/src/api.md +++ b/docs/src/api.md @@ -10,7 +10,9 @@ generate_module ## Generated modules Every generated module defines the types of the schema, `RootType` (the type of the root of -the schema), and the following functions and types. They are documented in the generated +the schema), and the following functions and types (with `validation = :separate`, +`validate`, `violations`, `isvalid` and `check_formats!` only when its validation file is +present, and `checks!` and `with_checks` not at all; with `validation = :none`, none of them). They are documented in the generated code, so in the REPL, `?readjson` shows their documentation once the module is loaded. | Name | Description | diff --git a/docs/src/guide.md b/docs/src/guide.md index 7a0db60..ff27c5d 100644 --- a/docs/src/guide.md +++ b/docs/src/guide.md @@ -119,6 +119,33 @@ checks off, building a `VolumeType` about 3 times less, and `setfields` on a hop (whose `amount` is `oneOf` a volume or a mass) about 7 times less. Validating the whole document takes about a quarter of the time it takes to read it. +## Minimal types, with the validation in a separate file + +With `validation = :separate`, the generated types are minimal: the same structs, with the +same constructors, which convert the values to the types of their fields but do not check +the constraints of the schema. Everything needed to check them (the constraints of each +type, the subschemas checked at runtime and the validator) goes in a separate file, +`validation.jl` (or `_validation.jl` next to the module file, without `split`), which +the module includes only if it is present: + +```julia +isfile(joinpath(@__DIR__, "validation.jl")) && include("validation.jl") +``` + +Without that file, the module only reads and writes. With it, it also has `validate(x)`, +`violations(x)` and `isvalid(x)`, and `tojson` and `writejson` validate before writing +(unless given `validate = false`). Reading is not checked: use `validate(readjson(T, file))` +for that. With `validation = :none`, the validation file is not written at all. + +The types still enforce the structure of the schema: the types of the properties, required +properties, the properties allowed and the enumeration types. A JSON value read into a +union of generated types (from `oneOf` or `anyOf`) gets the first option that fits by its +properties and the values of its enumerations (e.g. a `unit` that is `"l"` for a volume, `"kg"` +for a mass); options that only differ by other constraints cannot be told apart. + +For BeerJSON, the minimal module is 221 KiB of code, instead of 280 KiB, and the +validation file 90 KiB. + ## Type names Type names come from the definition names: `#/definitions/VolumeType` (or diff --git a/examples/generate_examples.jl b/examples/generate_examples.jl index 974dd12..8a17b7b 100644 --- a/examples/generate_examples.jl +++ b/examples/generate_examples.jl @@ -16,6 +16,10 @@ generate_module(ex("acme_schemas", "acme_flatschema.json"), joinpath(OUT, "AcmeF module_name = "AcmeFlat") generate_module(ex("acme_schemas", "acme_nestedschema.json"), joinpath(OUT, "AcmeNested.jl"); module_name = "AcmeNested") +# the same, with minimal types (constructors that only convert values) and the checks of the +# constraints in a separate, optional file, `AcmeNestedMinimal_validation.jl` +generate_module(ex("acme_schemas", "acme_nestedschema.json"), joinpath(OUT, "AcmeNestedMinimal.jl"); + module_name = "AcmeNestedMinimal", validation = :separate) generate_module(ex("acme_schemas", "acme_nestedschema_mod.json"), joinpath(OUT, "AcmeNestedMod.jl"); module_name = "AcmeNestedMod") generate_module(ex("acme_schemas", "acme_withreferenceschema.json"), joinpath(OUT, "AcmeWithReference.jl"); diff --git a/examples/generated/AcmeFlat.jl b/examples/generated/AcmeFlat.jl index 6111e9d..c34118c 100644 --- a/examples/generated/AcmeFlat.jl +++ b/examples/generated/AcmeFlat.jl @@ -5,12 +5,15 @@ module AcmeFlat using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export Product export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -46,52 +49,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -112,6 +79,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -128,18 +99,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -307,36 +266,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -395,7 +662,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -428,17 +695,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -719,7 +975,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -732,13 +987,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -788,12 +1036,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -965,29 +1218,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1002,183 +1232,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1241,7 +1294,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1291,9 +1344,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `acme_flatschema.json` diff --git a/examples/generated/AcmeNested.jl b/examples/generated/AcmeNested.jl index 90415dc..e84bafd 100644 --- a/examples/generated/AcmeNested.jl +++ b/examples/generated/AcmeNested.jl @@ -5,12 +5,15 @@ module AcmeNested using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export ProductDimensions, Product export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -46,52 +49,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -112,6 +79,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -128,18 +99,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -307,36 +266,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -395,7 +662,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -428,17 +695,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -719,7 +975,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -732,13 +987,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -788,12 +1036,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -965,29 +1218,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1002,183 +1232,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1241,7 +1294,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1291,9 +1344,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `acme_nestedschema.json` diff --git a/examples/generated/AcmeNestedMinimal.jl b/examples/generated/AcmeNestedMinimal.jl new file mode 100644 index 0000000..de86e76 --- /dev/null +++ b/examples/generated/AcmeNestedMinimal.jl @@ -0,0 +1,648 @@ +# This file was generated by JSONSchema2Types.jl from the JSON Schema +# `acme_nestedschema.json`. Do not edit it by hand: regenerate it instead. + +module AcmeNestedMinimal + +using JSON + +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError +export ProductDimensions, Product +export RootType + +# the constructors of the types do not check the constraints of the schema (generated +# with `validation = :separate`) +const _INLINE_CHECKS = false + +# --------------------------------------------------------------------------------------- +# Runtime support for generated types. +# +# This code is copied verbatim into every module generated by JSONSchema2Types, so that +# the generated module only depends on JSON.jl. It provides conversion of parsed JSON +# values into the generated types (with validation), and conversion back to JSON. +# --------------------------------------------------------------------------------------- + +""" + AbstractSchemaObject + +Supertype of all the structs generated from JSON Schema objects. +""" +abstract type AbstractSchemaObject end + +""" + AbstractSchemaEnum + +Supertype of all the types generated from JSON Schema `enum` (or `const`) keywords. +The wrapped value is in the field `value`. +""" +abstract type AbstractSchemaEnum end + +""" + SchemaValidationError(msg) + +Error thrown when a value does not conform to the JSON Schema it was generated from. +""" +struct SchemaValidationError <: Exception + msg::String +end +Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationError: ", e.msg) + +_jsfail(msg) = throw(SchemaValidationError(msg)) + +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. + +const _CHECKS = Ref(true) +const _VALIDATOR = Ref{Any}(nothing) + +# name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` +_jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : + T isa UnionAll || (T isa DataType && (isempty(T.parameters) || T <: AbstractSchemaObject)) ? + string(nameof(T)) : string(T) + +""" + _SPECS + +Metadata of the generated types, filled in right after each type definition. For a struct +`T`, `_SPECS[T]` is a named tuple with: + +* `fields`: for each field, its Julia `name`, its JSON `key`, whether it is `required` and + `nullable`, and its `constraints` (`minimum`, `pattern`...; and `schema`, the subschema + checked at runtime, if any); +* `additionalProperties`, and `extra`, the name of the field that keeps the properties not + described by the schema (or `nothing`); +* `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a + whole at runtime (or `nothing`). + +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + +For an enum type, `_SPECS[T]` holds the allowed `values`. +""" +const _SPECS = Dict{Any, Any}() + +# Constraints on the root of the schema when it is not a generated type (set by the generated +# code); checked by `fromdict(RootType, x)` and so by `fromjson` and `readjson`. +const _ROOT_CONSTRAINTS = Ref{Any}(nothing) + +# (the structs are parametric: their metadata is stored for the `UnionAll` type) +# (the generated code also defines a method of `_specs` for each struct returning its +# metadata as a constant, so that the checks are type-stable; this is the fallback) +_specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wrapper] + +# Metadata of each generated enum type: the allowed values. +_enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values + +# --- Conversion from parsed JSON values into Julia values --- + +""" + _jsfrom(T, x) + +Convert `x` into a value of type `T`, validating it against the schema; "from JSON". + +This is the core of reading documents and of the keyword constructors: every argument of +a generated constructor goes through `_jsfrom` with the type of its field, and reading a +document is `_jsfrom(RootType, JSON.parse(text))`. `x` can be: + +* a value of type `T`, returned as it is; +* a parsed JSON value, or a plain Julia one: a `Dict` or a named tuple for an object, a + vector for an array, a string, number, boolean or `nothing`. + +The conversion is recursive and depends on `T`: + +* a generated struct: from a dict, the keyword constructor is called with the properties + (unknown properties go to the extra field, or are an error); +* a generated enum type: its constructor, which checks the value; +* `Vector{S}`, `Dict{String, S}`, tuples: element by element; +* `String`, `Float64`, `Int64`, `Bool`, `Nothing`: checked, with numbers converted (`20` is a + valid `Float64`, `2.0` a valid `Int64`, but `2.5` is not); +* a `Union` (from `oneOf`, `anyOf`, optional fields...): the first option that works. + +Throws a [`SchemaValidationError`](@ref) when `x` does not fit. Its inverse is +[`_jsto`](@ref). +""" +function _jsfrom end + +_jsfrom(::Type{Any}, x) = x +_jsfrom(::Type{Nothing}, ::Nothing) = nothing +_jsfrom(::Type{Nothing}, x) = _jsfail("expected `null`, got $(repr(x))") + +_jsfrom(::Type{String}, x::AbstractString) = String(x) +_jsfrom(::Type{String}, x) = _jsfail("expected a string, got $(repr(x))") + +_jsfrom(::Type{Bool}, x::Bool) = x +_jsfrom(::Type{Bool}, x) = _jsfail("expected a boolean, got $(repr(x))") + +_jsfrom(::Type{Bool}, x::Real) = x isa Bool ? x : _jsfail("expected a boolean, got $(repr(x))") + +# Numbers: `T` is one of the numeric types `I <: Integer` (e.g. `Int64`, `Int128`, `BigInt`) +# or `T <: Real` (e.g. `Float64`, `BigFloat`, `Rational{BigInt}`) of the generated structs. +function _jsfrom(::Type{T}, x::Real) where {T <: Real} + x isa Bool && _jsfail("expected a number, got $(repr(x))") + x isa T && return x + try + return convert(T, x) + catch err + err isa InexactError || rethrow() + _jsfail("the number $(repr(x)) cannot be represented as `$(_jsname(T))`") + end +end +function _jsfrom(::Type{T}, x::Real) where {T <: Integer} + (x isa Bool || !isinteger(x)) && _jsfail("expected an integer, got $(repr(x))") + x isa T && return x + try + return convert(T, x) + catch err + err isa InexactError || rethrow() + _jsfail("the integer $(repr(x)) is out of the range of `$(_jsname(T))`") + end +end +_jsfrom(::Type{T}, x) where {T <: Real} = _jsfail("expected a number, got $(repr(x))") +_jsfrom(::Type{T}, x) where {T <: Integer} = _jsfail("expected an integer, got $(repr(x))") + +function _jsfrom(::Type{Vector{T}}, x) where {T} + x isa AbstractVector || _jsfail("expected an array, got $(repr(x))") + return T[_jsfrom(T, el) for el in x] +end + +# named tuples, such as `(unit = "l", value = 20)`, are accepted as objects +_jsobject(x) = x isa NamedTuple ? Dict{String, Any}(String(k) => v for (k, v) in pairs(x)) : x + +# tuples, from `prefixItems`, possibly ending with `Vararg{T}` for the remaining items +function _jsfrom(::Type{T}, x) where {T <: Tuple} + T isa Union && return _jsfromunion(T, x) + x isa T && return x + x isa Tuple && (x = collect(Any, x)) + x isa AbstractVector || _jsfail("expected an array, got $(repr(x))") + params = collect(Any, fieldtypes(Tuple{T.parameters[1:end-(Base.isvarargtype(last(T.parameters)) ? 1 : 0)]...})) + if !isempty(T.parameters) && Base.isvarargtype(last(T.parameters)) + length(x) >= length(params) || _jsfail("expected at least $(length(params)) items, got $(length(x))") + append!(params, fill(Base.unwrapva(last(T.parameters)), length(x) - length(params))) + else + length(x) == length(params) || _jsfail("expected $(length(params)) items, got $(length(x))") + end + return Tuple(_jsfrom(S, el) for (S, el) in zip(params, x)) +end + +function _jsfrom(::Type{Dict{String, T}}, x) where {T} + x = _jsobject(x) + x isa AbstractDict || _jsfail("expected an object, got $(repr(x))") + return Dict{String, T}(String(k) => _jsfrom(T, v) for (k, v) in x) +end + +function _jsfrom(::Type{T}, x) where {T <: AbstractSchemaEnum} + T isa Union && return _jsfromunion(T, x) + x isa T && return x + return T(x) +end + +function _jsfrom(::Type{T}, x) where {T <: AbstractSchemaObject} + T isa Union && return _jsfromunion(T, x) + x isa T && return x + x = _jsobject(x) + x isa AbstractDict || _jsfail("expected an object for `$(_jsname(T))`, got $(repr(x))") + spec = _specs(T) + extra = Dict{String, Any}() + for k in keys(x) + any(f -> f.key == k, spec.fields) && continue + spec.extra === nothing && _jsfail("unknown property `$k` for `$(_jsname(T))`") + extra[String(k)] = x[k] + end + kwargs = Pair{Symbol, Any}[] + for f in spec.fields + if haskey(x, f.key) + push!(kwargs, f.name => x[f.key]) + elseif f.required + _jsfail("missing required property `$(f.key)` for `$(_jsname(T))`") + end + end + spec.extra === nothing || push!(kwargs, spec.extra => extra) + return T(; kwargs...) +end + +""" + _jsmismatch(T, x) -> Union{Nothing, String} + +A quick check, without converting it, of whether the JSON object `x` surely cannot be +converted to the generated type `T`: a required property is missing, a property is +unknown, or the value of a property whose type is an enumeration is not one of its +values. Returns the reason, or `nothing` if `x` may be convertible (which only the +conversion decides). Used to skip, without the cost of an exception, the options of a +union, or of a `oneOf`/`anyOf`, that do not match, e.g. a volume for a mass. +""" +function _jsmismatch(::Type{T}, x::AbstractDict) where {T <: AbstractSchemaObject} + spec = _specs(T) + D = Base.unwrap_unionall(T) + for f in spec.fields + if haskey(x, f.key) + E = _jsnonnothing(fieldtype(D, f.name)) + v = x[f.key] + if E isa DataType && E <: AbstractSchemaEnum && !(v isa AbstractSchemaEnum) && !_jsenumok(E, v) + return _jsenummsg(E, v) + end + elseif f.required + return "missing required property `$(f.key)` for `$(_jsname(T))`" + end + end + if spec.extra === nothing + for k in keys(x) + any(f -> f.key == k, spec.fields) || return "unknown property `$k` for `$(_jsname(T))`" + end + end + return nothing +end +_jsmismatch(::Type, x) = nothing + +# the type of a field, without `Nothing` (a field type may be a type parameter, for numbers) +function _jsnonnothing(FT) + FT isa Union || return FT + ts = filter(!=(Nothing), Base.uniontypes(FT)) + return length(ts) == 1 ? only(ts) : Any +end + +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Types from `acme_nestedschema.json` +# --------------------------------------------------------------------------------------- + +""" + ProductDimensions(; kwargs...) + ProductDimensions{I, T}(; kwargs...) + +Dimensions of a product + +Integers are stored as `I <: Integer` and other numbers as `T <: Real`; by default, `Int64` +and `Float64`. + +# Fields + +- `length::T` (required) +- `width::T` (required) +- `height::T` (required) +- `_extra::Dict{String, Any}`: additional properties, not described in the schema +""" +struct ProductDimensions{I <: Integer, T <: Real} <: AbstractSchemaObject + length::T + width::T + height::T + _extra::Dict{String, Any} + function ProductDimensions{I, T}(; length, width, height, _extra = Dict{String, Any}()) where {I <: Integer, T <: Real} + length = _jsfrom(T, length) + width = _jsfrom(T, width) + height = _jsfrom(T, height) + _extra = _jsfrom(Dict{String, Any}, _extra) + return new(length, width, height, _extra) + end +end +ProductDimensions(; kwargs...) = ProductDimensions{Int64, Float64}(; kwargs...) +ProductDimensions{I, T}(length, width, height, _extra) where {I <: Integer, T <: Real} = ProductDimensions{I, T}(; length, width, height, _extra) +ProductDimensions(length, width, height, _extra) = ProductDimensions{_jsnumbertypes(length, width, height, _extra)...}(; length, width, height, _extra) +const _SPEC_ProductDimensions = ( + fields = ( + (name = :length, key = "length", required = true, nullable = false), + (name = :width, key = "width", required = true, nullable = false), + (name = :height, key = "height", required = true, nullable = false), + ), + extra = :_extra, +) +_specs(::Type{<:ProductDimensions}) = _SPEC_ProductDimensions +_SPECS[ProductDimensions] = _SPEC_ProductDimensions + +""" + Product(; kwargs...) + Product{I, T}(; kwargs...) + +A product from Acme's catalog + +Integers are stored as `I <: Integer` and other numbers as `T <: Real`; by default, `Int64` +and `Float64`. + +# Fields + +- `productId::I` (required): The unique identifier for a product +- `productName::String` (required): Name of the product +- `price::T` (required): The price of the product +- `tags::Union{Nothing, Vector{String}}`: Tags for the product +- `dimensions::Union{Nothing, ProductDimensions{I, T}}`: Dimensions of a product +- `_extra::Dict{String, Any}`: additional properties, not described in the schema +""" +struct Product{I <: Integer, T <: Real} <: AbstractSchemaObject + productId::I + productName::String + price::T + tags::Union{Nothing, Vector{String}} + dimensions::Union{Nothing, ProductDimensions{I, T}} + _extra::Dict{String, Any} + function Product{I, T}(; productId, productName, price, tags = nothing, dimensions = nothing, _extra = Dict{String, Any}()) where {I <: Integer, T <: Real} + productId = _jsfrom(I, productId) + productName = _jsfrom(String, productName) + price = _jsfrom(T, price) + tags = _jsfrom(Union{Nothing, Vector{String}}, tags) + dimensions = _jsfrom(Union{Nothing, ProductDimensions{I, T}}, dimensions) + _extra = _jsfrom(Dict{String, Any}, _extra) + return new(productId, productName, price, tags, dimensions, _extra) + end +end +Product(; kwargs...) = Product{Int64, Float64}(; kwargs...) +Product{I, T}(productId, productName, price, tags, dimensions, _extra) where {I <: Integer, T <: Real} = Product{I, T}(; productId, productName, price, tags, dimensions, _extra) +Product(productId, productName, price, tags, dimensions, _extra) = Product{_jsnumbertypes(productId, productName, price, tags, dimensions, _extra)...}(; productId, productName, price, tags, dimensions, _extra) +const _SPEC_Product = ( + fields = ( + (name = :productId, key = "productId", required = true, nullable = false), + (name = :productName, key = "productName", required = true, nullable = false), + (name = :price, key = "price", required = true, nullable = false), + (name = :tags, key = "tags", required = false, nullable = false), + (name = :dimensions, key = "dimensions", required = false, nullable = false), + ), + extra = :_extra, +) +_specs(::Type{<:Product}) = _SPEC_Product +_SPECS[Product] = _SPEC_Product + + +""" + RootType + +Alias of `Product`, the type of the root of the schema. +""" +const RootType = Product + +# The checks of the constraints of the schema, by `validate`, `violations` and `isvalid`, +# and before writing. Optional: without the file `AcmeNestedMinimal_validation.jl`, the module only +# reads and writes. +isfile(joinpath(@__DIR__, "AcmeNestedMinimal_validation.jl")) && include("AcmeNestedMinimal_validation.jl") + +end # module AcmeNestedMinimal diff --git a/examples/generated/AcmeNestedMinimal_validation.jl b/examples/generated/AcmeNestedMinimal_validation.jl new file mode 100644 index 0000000..354ac14 --- /dev/null +++ b/examples/generated/AcmeNestedMinimal_validation.jl @@ -0,0 +1,852 @@ +# This file is included by `AcmeNestedMinimal.jl`, generated by JSONSchema2Types.jl from the JSON +# Schema `acme_nestedschema.json`. Do not edit it by hand: regenerate it instead. +# +# The checks of the constraints of the schema: optional, see the end of `AcmeNestedMinimal.jl`. + +export validate, violations, check_formats! + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) + +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int +end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") + +# --- Validation of constraints --- + +_jslength(x::AbstractString) = length(x) + +# values of typed formats (dates, UUIDs) are validated through their string form +_jsscalar(x) = x + +# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`) +function _jsvalidate(x, c, where_; null_is_value::Bool = false) + c === nothing && return nothing + x === nothing && !null_is_value && return nothing + x = _jsscalar(x) + if haskey(c, :schema) + err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x)) + err === nothing || _jsfail("$where_ is invalid: $err") + end + if x isa Real && !(x isa Bool) + haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x") + haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x") + haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x") + haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x") + if haskey(c, :multipleOf) + q = x / c.multipleOf + isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x") + end + elseif x isa AbstractString + haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))") + haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))") + haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))") + elseif x isa AbstractVector + haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))") + haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))") + haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items") + if haskey(c, :items) + for (i, el) in enumerate(x) + _jsvalidate(el, c.items, _JSItem(where_, i)) + end + end + elseif x isa AbstractDict + haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties") + haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties") + end + return nothing +end + +""" + _jscheck(T, values, extra) + +Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the +converted field `values` and the additional properties `extra`. Called by the inner +constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that +required fields are set, the constraints of each field (`minimum`, `pattern`, +`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the +constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). +""" +function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} + _CHECKS[] || return nothing + spec = _vspecs(T) + nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) + spec.minProperties !== nothing && nprops < spec.minProperties && + _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") + spec.maxProperties !== nothing && nprops > spec.maxProperties && + _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops") + if spec.schema !== nothing + # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...) + obj = JSON.Object{String, Any}() + for (f, v) in zip(spec.fields, values) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra) + err = _jsvalid(spec.schema, obj) + err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err") + end + return nothing +end + +# The checks of the fields, unrolled over the tuples of field metadata and values (the +# metadata is a constant, so this is type-stable); returns the number of properties set. +@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0 +@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T} + f, v = first(fields), first(values) + if v === nothing && f.required && !f.nullable + _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`") + end + f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key)) + set = v !== nothing || (f.required && f.nullable) + return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) +end + +function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} + _CHECKS[] || return value + _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) + return value +end + +# --- Validation of JSON values against (sub)schemas --- +# +# The generated types enforce most of a schema by themselves. The remaining keywords (`not`, +# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are +# checked by validating the JSON form of a value against the corresponding subschemas, +# which the generator embeds (with their `$ref`s resolved) in the metadata of the types. + +""" + check_formats!(flag::Bool) + +Enable or disable the validation of the `format` keyword. Enabled by default. The formats of +JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`, +`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`, +`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`); +unknown formats are not. +""" +check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag) +const _CHECK_FORMATS = Ref(true) + +const _REGEX_CACHE = Dict{String, Regex}() + +# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without +# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at +# the end, after translating `\s` and long Unicode property names, which PCRE lacks. +const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX | + Base.PCRE.DOLLAR_ENDONLY +_jsregex(p::AbstractString) = + get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p) + +const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" +const _JS_PROPERTIES = Dict( + "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll", + "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M", + "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N", + "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No", + "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd", + "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi", + "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm", + "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z", + "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C", + "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co", + "Unassigned" => "Cn", +) + +function _jsecmaregex(p::AbstractString) + out = IOBuffer() + inclass = false + i = firstindex(p) + while i <= lastindex(p) + c = p[i] + if c == '\\' && i < lastindex(p) + n = p[nextind(p, i)] + j = nextind(p, nextind(p, i)) + if n == 's' + print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]") + elseif n == 'S' && !inclass + print(out, "[^", _JS_SPACES, "]") + elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{' + k = findnext('}', p, j) + k === nothing && (print(out, c, n); i = j; continue) + name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "") + print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}') + j = nextind(p, k) + else + print(out, c, n) + end + i = j + continue + end + # `[]` matches nothing and `[^]` anything, in ECMAScript + if !inclass && startswith(SubString(p, i), "[^]") + print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue + elseif !inclass && startswith(SubString(p, i), "[]") + print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue + end + c == '[' && (inclass = true) + c == ']' && (inclass = false) + print(out, c) + i = nextind(p, i) + end + return String(take!(out)) +end + +# --- Checks of the `format` keyword --- +# +# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not +# `$`, which allows a trailing newline) anchors the patterns. + +_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) + +function _jsdate(s) + m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s) + m === nothing && return false + y, mo, d = parse.(Int, m.captures) + days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) + return 1 <= mo <= 12 && 1 <= d <= days[mo] +end + +function _jstime(s) + m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s) + m === nothing && return false + h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3]) + oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8])) + (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false + if se == 60 + # a leap second is only at 23:59:60 UTC + utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60) + utc == 23 * 60 + 59 || return false + end + return true +end + +function _jsdatetime(s) + m = match(r"^([^Tt]*)[Tt](.*)\z", s) + return m !== nothing && _jsdate(m[1]) && _jstime(m[2]) +end + +function _jsipv4(s) + m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s) + m === nothing && return false + return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures) +end + +function _jsipv6(s) + (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false + parts = split(s, "::") + length(parts) > 2 && return false + groups(p) = isempty(p) ? String[] : split(p, ':') + gs = vcat([groups(p) for p in parts]...) + n = 0 + for (i, g) in enumerate(gs) + if occursin('.', g) + # an IPv4 address can only be the last group + (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false + n += 2 + else + occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false + n += 1 + end + end + return length(parts) == 2 ? n <= 7 : n == 8 +end + +function _jshostname(s) + isascii(s) || return false + s = endswith(s, ".") && length(s) > 1 ? chop(s) : s + (1 <= length(s) <= 253) || return false + for label in split(s, '.') + occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false + # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels + length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false + end + return true +end + +# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the +# IDNA2008 rules are not checked. +const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]") +const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z") + +function _jsidnhostname(s) + s = replace(s, _JS_IDN_DOTS => ".") + (1 <= length(s) <= 253) || return false + occursin(Regex("[\\s\u302E]"), s) && return false + for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.') + (1 <= length(label) <= 63) || return false + (startswith(label, "-") || endswith(label, "-")) && return false + occursin(_JS_IDN_LABEL, label) || return false + occursin(r"^\p{M}", label) && return false + end + return true +end + +const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]" + +function _jsemail(s; idn = false) + i = findlast('@', s) + i === nothing && return false + local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end] + atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT + dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z") + quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" : + r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z" + (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false + if startswith(domain, "[") && endswith(domain, "]") + lit = domain[2:end-1] + return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit) + end + endswith(domain, ".") && return false + return idn ? _jsidnhostname(domain) : _jshostname(domain) +end + +# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority +const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=" +function _jsuri(s; absolute = true, iri = false) + chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]" + occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false + m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s) + m === nothing && return false + absolute && m[1] === nothing && return false + # without a scheme, a first path segment with ':' would be read as a scheme + m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false + for part in (m[3], m[4], m[5]) + part === nothing || !occursin(r"[\[\]]", part) || return false + end + count('#', s) <= 1 || return false + if m[2] !== nothing + auth = m[2] + hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth) + hm === nothing && return false + if startswith(hm[1], "[") + h = hm[1][2:end-1] + (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false + end + end + return true +end + +_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s) +_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s) + +# RFC 6570: literals, and expressions `{[operator]varspec,...}` +const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" * + "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z") +_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s) + +# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months +const _JS_DURATION = let D = "[0-9]+", + time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)", + date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)" + Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z") +end +_jsduration(s) = occursin(_JS_DURATION, s) + +_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s) + +function _jsregexformat(s) + # syntax of PCRE (or Python) that ECMAScript does not have + occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false + try + _jsregex(s) + return true + catch + # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only + # for lookbehinds, which ECMAScript allows with variable width + return occursin("(?<", s) + end +end + +const _FORMATS = Dict{String, Function}( + "date-time" => _jsdatetime, + "date" => _jsdate, + "time" => _jstime, + "duration" => _jsduration, + "email" => _jsemail, + "idn-email" => s -> _jsemail(s; idn = true), + "hostname" => _jshostname, + "idn-hostname" => _jsidnhostname, + "ipv4" => _jsipv4, + "ipv6" => _jsipv6, + "uri" => _jsuri, + "uri-reference" => s -> _jsuri(s; absolute = false), + "iri" => s -> _jsuri(s; iri = true), + "iri-reference" => s -> _jsuri(s; absolute = false, iri = true), + "uri-template" => _jsuritemplate, + "json-pointer" => _jsjsonpointer, + "relative-json-pointer" => _jsreljsonpointer, + "uuid" => _jsuuid, + "regex" => _jsregexformat, +) + +_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) + +function _jstypeok(t::AbstractString, x) + t == "null" && return x === nothing + t == "boolean" && return x isa Bool + t == "integer" && return _jsisinteger(x) + t == "number" && return _jsisnumber(x) + t == "string" && return x isa AbstractString + t == "array" && return x isa AbstractVector + t == "object" && return x isa AbstractDict + return true +end + +function _jsallunique(x) + v = Any[_jsto(el) for el in x] + return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) +end + +""" + _jsvalid(schema, x) -> Union{Nothing, String} + +Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a +message describing the first problem found. +""" +_jsvalid(s, x) = first(_jsvalidann(s, x)) + +# Annotations collected while validating: the properties and array items that were +# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`. +_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items) +_jsbad(msg) = (msg, Set{String}(), Set{Int}()) + +""" + _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items) + +Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the +properties and the (1-based) indices of the items that the schema evaluated, as defined by +JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`. +""" +function _jsvalidann(s, x) + s === true && return _jsok() + s === false && return _jsbad("no value is allowed here") + s isa AbstractDict || return _jsok() + # A value of a generated type (from a field of a generated struct) is valid against + # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through + # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else. + if x isa AbstractSchemaObject + if haskey(s, "\$type") && length(s) == 1 + x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x)) + x = _jsto(x) + elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s)) + x = _jsto(x) + end + end + props = Set{String}() + items = Set{Int}() + addann!(ann) = (union!(props, ann[2]); union!(items, ann[3])) + + if haskey(s, "\$type") + # a generated type: the value must be convertible to it, which checks all of it + T = getfield(@__MODULE__, Symbol(s["\$type"])) + msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing + msg === nothing || return _jsbad(msg) + v = try + _jsfrom(T, x) + catch err + err isa SchemaValidationError || rethrow() + return _jsbad(err.msg) + end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end + x isa AbstractDict && union!(props, String.(keys(x))) + x isa AbstractVector && union!(items, eachindex(x)) + end + + if haskey(s, "type") + ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],) + any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))") + end + haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])") + haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))") + + if _jsisnumber(x) + haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])") + haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])") + haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) && + x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])") + haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) && + x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])") + if haskey(s, "multipleOf") + q = x / s["multipleOf"] + isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])") + end + elseif x isa AbstractString + haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])") + haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])") + haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) && + return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])") + if haskey(s, "format") && _CHECK_FORMATS[] + check = get(_FORMATS, s["format"], nothing) + check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])") + end + elseif x isa AbstractVector + haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items") + haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items") + if get(s, "uniqueItems", false) === true + for i in eachindex(x), j in firstindex(x):i-1 + _jseq(x[i], x[j]) && return _jsbad("items are not unique") + end + end + prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[]) + for (i, sub) in enumerate(prefix) + i <= length(x) || break + err = _jsvalid(sub, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + rest = haskey(s, "prefixItems") ? get(s, "items", nothing) : + get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing) + if rest !== nothing + for i in (length(prefix) + 1):length(x) + err = _jsvalid(rest, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + end + if haskey(s, "contains") + matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing] + n = length(matching) + lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int)) + lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi") + union!(items, matching) + end + elseif x isa AbstractDict + haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties") + haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties") + for k in get(s, "required", ()) + haskey(x, k) || return _jsbad("missing required property `$k`") + end + defined = get(s, "properties", nothing) + patterns = get(s, "patternProperties", nothing) + extra = get(s, "additionalProperties", nothing) + names = get(s, "propertyNames", nothing) + (defined === nothing && patterns === nothing && extra === nothing && names === nothing) || + for (k, v) in x + k = String(k) + matched = false + if defined !== nothing && haskey(defined, k) + matched = true + err = _jsvalid(defined[k], v) + err === nothing || return _jsbad("property `$k`: $err") + end + for (p, sub) in something(patterns, ()) + occursin(_jsregex(p), k) || continue + matched = true + err = _jsvalid(sub, v) + err === nothing || return _jsbad("property `$k`: $err") + end + if !matched && extra !== nothing + err = _jsvalid(extra, v) + err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err") + matched = true + end + matched && push!(props, k) + if names !== nothing + err = _jsvalid(names, k) + err === nothing || return _jsbad("property name `$k`: $err") + end + end + (haskey(s, "dependentRequired") || haskey(s, "dependencies")) && + for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict()))) + haskey(x, k) || continue + for d in deps + haskey(x, d) || return _jsbad("property `$k` requires property `$d`") + end + end + (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) && + for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict()))) + haskey(x, k) || continue + ann = _jsvalidann(sub, x) + ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])") + addann!(ann) + end + end + + for sub in get(s, "allOf", ()) + ann = _jsvalidann(sub, x) + ann[1] === nothing || return ann + addann!(ann) + end + if haskey(s, "anyOf") + anns = [_jsvalidann(sub, x) for sub in s["anyOf"]] + valid = filter(a -> a[1] === nothing, anns) + isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")") + foreach(addann!, valid) + end + if haskey(s, "oneOf") + valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]]) + n = length(valid) + n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" : + "matches $n options of `oneOf`, but must match exactly one") + addann!(only(valid)) + end + haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`") + if haskey(s, "if") + cond = _jsvalidann(s["if"], x) + if cond[1] === nothing + addann!(cond) + if haskey(s, "then") + ann = _jsvalidann(s["then"], x) + ann[1] === nothing || return _jsbad("`then`: " * ann[1]) + addann!(ann) + end + elseif haskey(s, "else") + ann = _jsvalidann(s["else"], x) + ann[1] === nothing || return _jsbad("`else`: " * ann[1]) + addann!(ann) + end + end + + # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this + # schema, or of its valid subschemas, evaluated + if x isa AbstractVector && haskey(s, "unevaluatedItems") + for i in eachindex(x) + i in items && continue + err = _jsvalid(s["unevaluatedItems"], x[i]) + err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err") + push!(items, i) + end + end + if x isa AbstractDict && haskey(s, "unevaluatedProperties") + for (k, v) in x + String(k) in props && continue + err = _jsvalid(s["unevaluatedProperties"], v) + err === nothing || return _jsbad(s["unevaluatedProperties"] === false ? + "property `$k` is not allowed" : "property `$k`: $err") + push!(props, String(k)) + end + end + return (nothing, props, items) +end + +# the JSON names of the properties of a value of a generated type +function _jskeys(x::T) where {T <: AbstractSchemaObject} + spec = _specs(T) + ks = Set{String}() + for f in spec.fields + v = getfield(x, f.name) + (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key) + end + if spec.extra !== nothing + union!(ks, keys(getfield(x, spec.extra))) + end + return ks +end + +# --- Validation of whole values --- + +""" + violations(x) -> Vector{String} + +Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every +value nested in it, against all the constraints of the schema, whether or not the checks +were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per +invalid value (the first problem of each), with its location, e.g. +`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON +names of the properties and 1-based indices of the items: `recipes[1].batch_size`. +""" +function violations(x) + out = String[] + with_checks(true) do + _jscollect!(out, x, Any[]) + if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing + try + _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + catch err + err isa SchemaValidationError || rethrow() + push!(out, err.msg) + end + end + end + return out +end + +""" + validate(x) + +Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing +the problems found, if any. Returns `x`. +""" +validate(x) = _jsvalidateall(x) + +function _jsvalidateall(x) + v = violations(x) + isempty(v) && return x + n = length(v) + _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n " * join(v, "\n ")) +end + +""" + isvalid(x::AbstractSchemaObject) -> Bool + +Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref). +""" +Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x)) + +# The location of a value is kept as a stack of property names and indices, and only +# written out (e.g. `recipes[1].batch_size`) when a problem is found. +function _jsat(path::Vector{Any}, msg) + isempty(path) && return msg + io = IOBuffer() + for (i, p) in enumerate(path) + p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p) + end + return String(take!(io)) * ": " * msg +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} + spec = _vspecs(T) + values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) + extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) + try + _jscheck(T, values, extra) + catch err + err isa SchemaValidationError || rethrow() + push!(out, _jsat(path, err.msg)) + end + _jscollectfields!(out, spec.fields, values, path) + extra === nothing || _jscollect!(out, extra, path) + return out +end + +# (unrolled over the tuples of field metadata and values, as `_jscheckfields`) +@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out +@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path) + v = first(values) + if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} + push!(path, first(fields).key) + _jscollect!(out, v, path) + pop!(path) + end + return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path) +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum} + _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value))) + return out +end +function _jscollect!(out, x::Union{AbstractVector, Tuple}, path) + for (i, v) in enumerate(x) + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, i) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +function _jscollect!(out, x::AbstractDict, path) + for (k, v) in x + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, String(k)) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +_jscollect!(out, x, path) = out + +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall + +# Metadata of the types, with their constraints + +const _VSPEC_ProductDimensions = ( + fields = ( + (name = :length, key = "length", required = true, nullable = false, constraints = nothing), + (name = :width, key = "width", required = true, nullable = false, constraints = nothing), + (name = :height, key = "height", required = true, nullable = false, constraints = nothing), + ), + additionalProperties = true, + extra = :_extra, + minProperties = nothing, + maxProperties = nothing, + schema = nothing, +) +_vspecs(::Type{<:ProductDimensions}) = _VSPEC_ProductDimensions + +const _VSPEC_Product = ( + fields = ( + (name = :productId, key = "productId", required = true, nullable = false, constraints = nothing), + (name = :productName, key = "productName", required = true, nullable = false, constraints = nothing), + (name = :price, key = "price", required = true, nullable = false, constraints = (exclusiveMinimum = 0,)), + (name = :tags, key = "tags", required = false, nullable = false, constraints = (minItems = 1, uniqueItems = true,)), + (name = :dimensions, key = "dimensions", required = false, nullable = false, constraints = nothing), + ), + additionalProperties = true, + extra = :_extra, + minProperties = nothing, + maxProperties = nothing, + schema = nothing, +) +_vspecs(::Type{<:Product}) = _VSPEC_Product + diff --git a/examples/generated/AcmeNestedMod.jl b/examples/generated/AcmeNestedMod.jl index b64e3e2..d09a1eb 100644 --- a/examples/generated/AcmeNestedMod.jl +++ b/examples/generated/AcmeNestedMod.jl @@ -5,12 +5,15 @@ module AcmeNestedMod using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export ProductDimensions, Product export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -46,52 +49,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -112,6 +79,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -128,18 +99,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -307,36 +266,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -395,7 +662,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -428,17 +695,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -719,7 +975,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -732,13 +987,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -788,12 +1036,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -965,29 +1218,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1002,183 +1232,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1241,7 +1294,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1291,9 +1344,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `acme_nestedschema_mod.json` diff --git a/examples/generated/AcmeWithReference.jl b/examples/generated/AcmeWithReference.jl index 92c8b7d..81caf21 100644 --- a/examples/generated/AcmeWithReference.jl +++ b/examples/generated/AcmeWithReference.jl @@ -5,12 +5,15 @@ module AcmeWithReference using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export LongitudeAndLatitude, ProductDimensions, Product export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -46,52 +49,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -112,6 +79,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -128,18 +99,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -307,36 +266,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -395,7 +662,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -428,17 +695,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -719,7 +975,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -732,13 +987,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -788,12 +1036,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -965,29 +1218,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1002,183 +1232,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1241,7 +1294,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1291,9 +1344,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `acme_tobereferredschema.json` diff --git a/examples/generated/BeerJSONTypes/BeerJSONTypes.jl b/examples/generated/BeerJSONTypes/BeerJSONTypes.jl index 3168e2e..f55b275 100644 --- a/examples/generated/BeerJSONTypes/BeerJSONTypes.jl +++ b/examples/generated/BeerJSONTypes/BeerJSONTypes.jl @@ -5,8 +5,8 @@ module BeerJSONTypes using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export TimeUnitType, GravityUnitType, AcidityUnitType, PercentUnitType, ColorUnitType, DiastaticPowerUnitType export VolumeUnitType, MassUnitType, ViscosityUnitType, ConcentrationUnitType, UnitUnitType, TemperatureUnitType @@ -26,7 +26,11 @@ export TasteType, RecipeType, EquipmentFormEnum, EquipmentItemType, EquipmentTyp export BeerJSON export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + include("runtime.jl") +include("runtime_validation.jl") # Generated types, one file per schema file, in dependency order include("measureable_units.jl") diff --git a/examples/generated/BeerJSONTypes/runtime.jl b/examples/generated/BeerJSONTypes/runtime.jl index 48c0ccc..d564392 100644 --- a/examples/generated/BeerJSONTypes/runtime.jl +++ b/examples/generated/BeerJSONTypes/runtime.jl @@ -36,52 +36,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -102,6 +66,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -118,18 +86,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -308,7 +264,7 @@ function _jsfromunion(::Type{T}, x) where {T} options = Base.uniontypes(T) x === nothing && Nothing in options && return nothing # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 return with_checks(() -> _jsfromunion(T, x), true) end msgs = String[] @@ -328,97 +284,9 @@ function _jsfromunion(::Type{T}, x) where {T} _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) end -# --- Validation of constraints --- - -_jslength(x::AbstractString) = length(x) - -# values of typed formats (dates, UUIDs) are validated through their string form -_jsscalar(x) = x - -# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`) -function _jsvalidate(x, c, where_; null_is_value::Bool = false) - c === nothing && return nothing - x === nothing && !null_is_value && return nothing - x = _jsscalar(x) - if haskey(c, :schema) - err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x)) - err === nothing || _jsfail("$where_ is invalid: $err") - end - if x isa Real && !(x isa Bool) - haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x") - haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x") - haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x") - haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x") - if haskey(c, :multipleOf) - q = x / c.multipleOf - isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x") - end - elseif x isa AbstractString - haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))") - haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))") - haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))") - elseif x isa AbstractVector - haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))") - haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))") - haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items") - if haskey(c, :items) - for (i, el) in enumerate(x) - _jsvalidate(el, c.items, _JSItem(where_, i)) - end - end - elseif x isa AbstractDict - haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties") - haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties") - end - return nothing -end - -""" - _jscheck(T, values, extra) - -Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the -converted field `values` and the additional properties `extra`. Called by the inner -constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that -required fields are set, the constraints of each field (`minimum`, `pattern`, -`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the -constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). -""" -function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} - _CHECKS[] || return nothing - spec = _specs(T) - nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) - spec.minProperties !== nothing && nprops < spec.minProperties && - _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") - spec.maxProperties !== nothing && nprops > spec.maxProperties && - _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops") - if spec.schema !== nothing - # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...) - obj = JSON.Object{String, Any}() - for (f, v) in zip(spec.fields, values) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra) - err = _jsvalid(spec.schema, obj) - err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err") - end - return nothing -end - -# The checks of the fields, unrolled over the tuples of field metadata and values (the -# metadata is a constant, so this is type-stable); returns the number of properties set. -@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0 -@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T} - f, v = first(fields), first(values) - if v === nothing && f.required && !f.nullable - _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`") - end - f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key)) - set = v !== nothing || (f.required && f.nullable) - return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) -end +# --- Values of enumerations --- -# Called by the inner constructors of the generated enum types. +# (used to choose an option of a union when reading, and by the checks) # (strings are compared directly; other values with the equality of JSON values) function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} vals = _enumvalues(T) @@ -429,299 +297,8 @@ end _jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" -function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} - _CHECKS[] || return value - _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) - return value -end - -# --- Validation of JSON values against (sub)schemas --- -# -# The generated types enforce most of a schema by themselves. The remaining keywords (`not`, -# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are -# checked by validating the JSON form of a value against the corresponding subschemas, -# which the generator embeds (with their `$ref`s resolved) in the metadata of the types. - -""" - check_formats!(flag::Bool) - -Enable or disable the validation of the `format` keyword. Enabled by default. The formats of -JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`, -`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`, -`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`); -unknown formats are not. -""" -check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag) -const _CHECK_FORMATS = Ref(true) - -const _REGEX_CACHE = Dict{String, Regex}() - -# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without -# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at -# the end, after translating `\s` and long Unicode property names, which PCRE lacks. -const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX | - Base.PCRE.DOLLAR_ENDONLY -_jsregex(p::AbstractString) = - get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p) - -const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" -const _JS_PROPERTIES = Dict( - "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll", - "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M", - "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N", - "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No", - "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd", - "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi", - "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm", - "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z", - "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C", - "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co", - "Unassigned" => "Cn", -) - -function _jsecmaregex(p::AbstractString) - out = IOBuffer() - inclass = false - i = firstindex(p) - while i <= lastindex(p) - c = p[i] - if c == '\\' && i < lastindex(p) - n = p[nextind(p, i)] - j = nextind(p, nextind(p, i)) - if n == 's' - print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]") - elseif n == 'S' && !inclass - print(out, "[^", _JS_SPACES, "]") - elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{' - k = findnext('}', p, j) - k === nothing && (print(out, c, n); i = j; continue) - name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "") - print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}') - j = nextind(p, k) - else - print(out, c, n) - end - i = j - continue - end - # `[]` matches nothing and `[^]` anything, in ECMAScript - if !inclass && startswith(SubString(p, i), "[^]") - print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue - elseif !inclass && startswith(SubString(p, i), "[]") - print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue - end - c == '[' && (inclass = true) - c == ']' && (inclass = false) - print(out, c) - i = nextind(p, i) - end - return String(take!(out)) -end - -# --- Checks of the `format` keyword --- -# -# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not -# `$`, which allows a trailing newline) anchors the patterns. - -_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) - -function _jsdate(s) - m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s) - m === nothing && return false - y, mo, d = parse.(Int, m.captures) - days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) - return 1 <= mo <= 12 && 1 <= d <= days[mo] -end - -function _jstime(s) - m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s) - m === nothing && return false - h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3]) - oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8])) - (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false - if se == 60 - # a leap second is only at 23:59:60 UTC - utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60) - utc == 23 * 60 + 59 || return false - end - return true -end - -function _jsdatetime(s) - m = match(r"^([^Tt]*)[Tt](.*)\z", s) - return m !== nothing && _jsdate(m[1]) && _jstime(m[2]) -end - -function _jsipv4(s) - m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s) - m === nothing && return false - return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures) -end - -function _jsipv6(s) - (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false - parts = split(s, "::") - length(parts) > 2 && return false - groups(p) = isempty(p) ? String[] : split(p, ':') - gs = vcat([groups(p) for p in parts]...) - n = 0 - for (i, g) in enumerate(gs) - if occursin('.', g) - # an IPv4 address can only be the last group - (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false - n += 2 - else - occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false - n += 1 - end - end - return length(parts) == 2 ? n <= 7 : n == 8 -end - -function _jshostname(s) - isascii(s) || return false - s = endswith(s, ".") && length(s) > 1 ? chop(s) : s - (1 <= length(s) <= 253) || return false - for label in split(s, '.') - occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false - # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels - length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false - end - return true -end - -# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the -# IDNA2008 rules are not checked. -const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]") -const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z") - -function _jsidnhostname(s) - s = replace(s, _JS_IDN_DOTS => ".") - (1 <= length(s) <= 253) || return false - occursin(Regex("[\\s\u302E]"), s) && return false - for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.') - (1 <= length(label) <= 63) || return false - (startswith(label, "-") || endswith(label, "-")) && return false - occursin(_JS_IDN_LABEL, label) || return false - occursin(r"^\p{M}", label) && return false - end - return true -end - -const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]" - -function _jsemail(s; idn = false) - i = findlast('@', s) - i === nothing && return false - local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end] - atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT - dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z") - quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" : - r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z" - (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false - if startswith(domain, "[") && endswith(domain, "]") - lit = domain[2:end-1] - return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit) - end - endswith(domain, ".") && return false - return idn ? _jsidnhostname(domain) : _jshostname(domain) -end - -# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority -const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=" -function _jsuri(s; absolute = true, iri = false) - chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]" - occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false - m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s) - m === nothing && return false - absolute && m[1] === nothing && return false - # without a scheme, a first path segment with ':' would be read as a scheme - m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false - for part in (m[3], m[4], m[5]) - part === nothing || !occursin(r"[\[\]]", part) || return false - end - count('#', s) <= 1 || return false - if m[2] !== nothing - auth = m[2] - hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth) - hm === nothing && return false - if startswith(hm[1], "[") - h = hm[1][2:end-1] - (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false - end - end - return true -end - -_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s) -_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s) - -# RFC 6570: literals, and expressions `{[operator]varspec,...}` -const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" * - "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * - "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * - "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z") -_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s) - -# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months -const _JS_DURATION = let D = "[0-9]+", - time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)", - date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)" - Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z") -end -_jsduration(s) = occursin(_JS_DURATION, s) - -_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s) - -function _jsregexformat(s) - # syntax of PCRE (or Python) that ECMAScript does not have - occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false - try - _jsregex(s) - return true - catch - # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only - # for lookbehinds, which ECMAScript allows with variable width - return occursin("(?<", s) - end -end - -const _FORMATS = Dict{String, Function}( - "date-time" => _jsdatetime, - "date" => _jsdate, - "time" => _jstime, - "duration" => _jsduration, - "email" => _jsemail, - "idn-email" => s -> _jsemail(s; idn = true), - "hostname" => _jshostname, - "idn-hostname" => _jsidnhostname, - "ipv4" => _jsipv4, - "ipv6" => _jsipv6, - "uri" => _jsuri, - "uri-reference" => s -> _jsuri(s; absolute = false), - "iri" => s -> _jsuri(s; iri = true), - "iri-reference" => s -> _jsuri(s; absolute = false, iri = true), - "uri-template" => _jsuritemplate, - "json-pointer" => _jsjsonpointer, - "relative-json-pointer" => _jsreljsonpointer, - "uuid" => _jsuuid, - "regex" => _jsregexformat, -) - -_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) _jsisnumber(x) = x isa Real && !(x isa Bool) -function _jstypeok(t::AbstractString, x) - t == "null" && return x === nothing - t == "boolean" && return x isa Bool - t == "integer" && return _jsisinteger(x) - t == "number" && return _jsisnumber(x) - t == "string" && return x isa AbstractString - t == "array" && return x isa AbstractVector - t == "object" && return x isa AbstractDict - return true -end - # equality of JSON values: `1 == 1.0`, but `true != 1` _jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) @@ -729,232 +306,6 @@ _jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jse _jseq(a::AbstractDict, b::AbstractDict) = length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) -function _jsallunique(x) - v = Any[_jsto(el) for el in x] - return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) -end - -""" - _jsvalid(schema, x) -> Union{Nothing, String} - -Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a -message describing the first problem found. -""" -_jsvalid(s, x) = first(_jsvalidann(s, x)) - -# Annotations collected while validating: the properties and array items that were -# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`. -_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items) -_jsbad(msg) = (msg, Set{String}(), Set{Int}()) - -""" - _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items) - -Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the -properties and the (1-based) indices of the items that the schema evaluated, as defined by -JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`. -""" -function _jsvalidann(s, x) - s === true && return _jsok() - s === false && return _jsbad("no value is allowed here") - s isa AbstractDict || return _jsok() - # A value of a generated type (from a field of a generated struct) is valid against - # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through - # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else. - if x isa AbstractSchemaObject - if haskey(s, "\$type") && length(s) == 1 - x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x)) - x = _jsto(x) - elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s)) - x = _jsto(x) - end - end - props = Set{String}() - items = Set{Int}() - addann!(ann) = (union!(props, ann[2]); union!(items, ann[3])) - - if haskey(s, "\$type") - # a generated type: the value must be convertible to it, which checks all of it - T = getfield(@__MODULE__, Symbol(s["\$type"])) - msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing - msg === nothing || return _jsbad(msg) - try - _jsfrom(T, x) - catch err - err isa SchemaValidationError || rethrow() - return _jsbad(err.msg) - end - x isa AbstractDict && union!(props, String.(keys(x))) - x isa AbstractVector && union!(items, eachindex(x)) - end - - if haskey(s, "type") - ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],) - any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))") - end - haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])") - haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))") - - if _jsisnumber(x) - haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])") - haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])") - haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) && - x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])") - haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) && - x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])") - if haskey(s, "multipleOf") - q = x / s["multipleOf"] - isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])") - end - elseif x isa AbstractString - haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])") - haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])") - haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) && - return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])") - if haskey(s, "format") && _CHECK_FORMATS[] - check = get(_FORMATS, s["format"], nothing) - check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])") - end - elseif x isa AbstractVector - haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items") - haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items") - if get(s, "uniqueItems", false) === true - for i in eachindex(x), j in firstindex(x):i-1 - _jseq(x[i], x[j]) && return _jsbad("items are not unique") - end - end - prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[]) - for (i, sub) in enumerate(prefix) - i <= length(x) || break - err = _jsvalid(sub, x[i]) - err === nothing || return _jsbad("item $i: $err") - push!(items, i) - end - rest = haskey(s, "prefixItems") ? get(s, "items", nothing) : - get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing) - if rest !== nothing - for i in (length(prefix) + 1):length(x) - err = _jsvalid(rest, x[i]) - err === nothing || return _jsbad("item $i: $err") - push!(items, i) - end - end - if haskey(s, "contains") - matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing] - n = length(matching) - lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int)) - lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi") - union!(items, matching) - end - elseif x isa AbstractDict - haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties") - haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties") - for k in get(s, "required", ()) - haskey(x, k) || return _jsbad("missing required property `$k`") - end - defined = get(s, "properties", nothing) - patterns = get(s, "patternProperties", nothing) - extra = get(s, "additionalProperties", nothing) - names = get(s, "propertyNames", nothing) - (defined === nothing && patterns === nothing && extra === nothing && names === nothing) || - for (k, v) in x - k = String(k) - matched = false - if defined !== nothing && haskey(defined, k) - matched = true - err = _jsvalid(defined[k], v) - err === nothing || return _jsbad("property `$k`: $err") - end - for (p, sub) in something(patterns, ()) - occursin(_jsregex(p), k) || continue - matched = true - err = _jsvalid(sub, v) - err === nothing || return _jsbad("property `$k`: $err") - end - if !matched && extra !== nothing - err = _jsvalid(extra, v) - err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err") - matched = true - end - matched && push!(props, k) - if names !== nothing - err = _jsvalid(names, k) - err === nothing || return _jsbad("property name `$k`: $err") - end - end - (haskey(s, "dependentRequired") || haskey(s, "dependencies")) && - for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict()))) - haskey(x, k) || continue - for d in deps - haskey(x, d) || return _jsbad("property `$k` requires property `$d`") - end - end - (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) && - for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict()))) - haskey(x, k) || continue - ann = _jsvalidann(sub, x) - ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])") - addann!(ann) - end - end - - for sub in get(s, "allOf", ()) - ann = _jsvalidann(sub, x) - ann[1] === nothing || return ann - addann!(ann) - end - if haskey(s, "anyOf") - anns = [_jsvalidann(sub, x) for sub in s["anyOf"]] - valid = filter(a -> a[1] === nothing, anns) - isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")") - foreach(addann!, valid) - end - if haskey(s, "oneOf") - valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]]) - n = length(valid) - n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" : - "matches $n options of `oneOf`, but must match exactly one") - addann!(only(valid)) - end - haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`") - if haskey(s, "if") - cond = _jsvalidann(s["if"], x) - if cond[1] === nothing - addann!(cond) - if haskey(s, "then") - ann = _jsvalidann(s["then"], x) - ann[1] === nothing || return _jsbad("`then`: " * ann[1]) - addann!(ann) - end - elseif haskey(s, "else") - ann = _jsvalidann(s["else"], x) - ann[1] === nothing || return _jsbad("`else`: " * ann[1]) - addann!(ann) - end - end - - # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this - # schema, or of its valid subschemas, evaluated - if x isa AbstractVector && haskey(s, "unevaluatedItems") - for i in eachindex(x) - i in items && continue - err = _jsvalid(s["unevaluatedItems"], x[i]) - err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err") - push!(items, i) - end - end - if x isa AbstractDict && haskey(s, "unevaluatedProperties") - for (k, v) in x - String(k) in props && continue - err = _jsvalid(s["unevaluatedProperties"], v) - err === nothing || return _jsbad(s["unevaluatedProperties"] === false ? - "property `$k` is not allowed" : "property `$k`: $err") - push!(props, String(k)) - end - end - return (nothing, props, items) -end - # --- Conversion from Julia values into JSON-compatible values --- """ @@ -978,20 +329,6 @@ _jsto(x::AbstractVector) = Any[_jsto(el) for el in x] _jsto(x::Tuple) = Any[_jsto(el) for el in x] _jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) -# the JSON names of the properties of a value of a generated type -function _jskeys(x::T) where {T <: AbstractSchemaObject} - spec = _specs(T) - ks = Set{String}() - for f in spec.fields - v = getfield(x, f.name) - (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key) - end - if spec.extra !== nothing - union!(ks, keys(getfield(x, spec.extra))) - end - return ks -end - function _jsto(x::T) where {T <: AbstractSchemaObject} obj = JSON.Object{String, Any}() for f in _specs(T).fields @@ -1066,7 +403,7 @@ validating it against the constraints of the schema. function fromdict(::Type{T}, x) where {T} value = _jsfrom(T, x) # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) end return value @@ -1144,23 +481,34 @@ Read the JSON file `filename` into a value of type `T`. readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) """ - tojson(x; pretty=false, validate=!checks()) + tojson(x; pretty=false, validate) -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). """ -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) return JSON.json(todict(x); pretty) end +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + """ - writejson(filename, x; pretty=true, validate=!checks()) + writejson(filename, x; pretty=true, validate) -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. """ -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) json = tojson(x; pretty, validate) open(filename, "w") do io write(io, json) @@ -1169,118 +517,6 @@ function writejson(filename::AbstractString, x; pretty::Bool = true, validate::B return filename end -# --- Validation of whole values --- - -""" - violations(x) -> Vector{String} - -Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every -value nested in it, against all the constraints of the schema, whether or not the checks -were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per -invalid value (the first problem of each), with its location, e.g. -`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON -names of the properties and 1-based indices of the items: `recipes[1].batch_size`. -""" -function violations(x) - out = String[] - with_checks(true) do - _jscollect!(out, x, Any[]) - if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing - try - _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - catch err - err isa SchemaValidationError || rethrow() - push!(out, err.msg) - end - end - end - return out -end - -""" - validate(x) - -Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing -the problems found, if any. Returns `x`. -""" -validate(x) = _jsvalidateall(x) - -function _jsvalidateall(x) - v = violations(x) - isempty(v) && return x - n = length(v) - _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n " * join(v, "\n ")) -end - -""" - isvalid(x::AbstractSchemaObject) -> Bool - -Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref). -""" -Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x)) - -# The location of a value is kept as a stack of property names and indices, and only -# written out (e.g. `recipes[1].batch_size`) when a problem is found. -function _jsat(path::Vector{Any}, msg) - isempty(path) && return msg - io = IOBuffer() - for (i, p) in enumerate(path) - p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p) - end - return String(take!(io)) * ": " * msg -end - -function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) - values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) - extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) - try - _jscheck(T, values, extra) - catch err - err isa SchemaValidationError || rethrow() - push!(out, _jsat(path, err.msg)) - end - _jscollectfields!(out, spec.fields, values, path) - extra === nothing || _jscollect!(out, extra, path) - return out -end - -# (unrolled over the tuples of field metadata and values, as `_jscheckfields`) -@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out -@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path) - v = first(values) - if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} - push!(path, first(fields).key) - _jscollect!(out, v, path) - pop!(path) - end - return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path) -end - -function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum} - _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value))) - return out -end -function _jscollect!(out, x::Union{AbstractVector, Tuple}, path) - for (i, v) in enumerate(x) - v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue - push!(path, i) - _jscollect!(out, v, path) - pop!(path) - end - return out -end -function _jscollect!(out, x::AbstractDict, path) - for (k, v) in x - v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue - push!(path, String(k)) - _jscollect!(out, v, path) - pop!(path) - end - return out -end -_jscollect!(out, x, path) = out - # --------------------------------------------------------------------------------------- # End of runtime support. Generated types follow. # --------------------------------------------------------------------------------------- diff --git a/examples/generated/BeerJSONTypes/runtime_validation.jl b/examples/generated/BeerJSONTypes/runtime_validation.jl new file mode 100644 index 0000000..7969b4d --- /dev/null +++ b/examples/generated/BeerJSONTypes/runtime_validation.jl @@ -0,0 +1,815 @@ +# This file is included by `BeerJSONTypes.jl`, generated by JSONSchema2Types.jl from the JSON +# Schema `beer.json`. Do not edit it by hand: regenerate it instead. + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) + +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int +end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") + +# --- Validation of constraints --- + +_jslength(x::AbstractString) = length(x) + +# values of typed formats (dates, UUIDs) are validated through their string form +_jsscalar(x) = x + +# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`) +function _jsvalidate(x, c, where_; null_is_value::Bool = false) + c === nothing && return nothing + x === nothing && !null_is_value && return nothing + x = _jsscalar(x) + if haskey(c, :schema) + err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x)) + err === nothing || _jsfail("$where_ is invalid: $err") + end + if x isa Real && !(x isa Bool) + haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x") + haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x") + haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x") + haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x") + if haskey(c, :multipleOf) + q = x / c.multipleOf + isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x") + end + elseif x isa AbstractString + haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))") + haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))") + haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))") + elseif x isa AbstractVector + haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))") + haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))") + haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items") + if haskey(c, :items) + for (i, el) in enumerate(x) + _jsvalidate(el, c.items, _JSItem(where_, i)) + end + end + elseif x isa AbstractDict + haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties") + haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties") + end + return nothing +end + +""" + _jscheck(T, values, extra) + +Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the +converted field `values` and the additional properties `extra`. Called by the inner +constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that +required fields are set, the constraints of each field (`minimum`, `pattern`, +`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the +constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). +""" +function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} + _CHECKS[] || return nothing + spec = _vspecs(T) + nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) + spec.minProperties !== nothing && nprops < spec.minProperties && + _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") + spec.maxProperties !== nothing && nprops > spec.maxProperties && + _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops") + if spec.schema !== nothing + # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...) + obj = JSON.Object{String, Any}() + for (f, v) in zip(spec.fields, values) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra) + err = _jsvalid(spec.schema, obj) + err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err") + end + return nothing +end + +# The checks of the fields, unrolled over the tuples of field metadata and values (the +# metadata is a constant, so this is type-stable); returns the number of properties set. +@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0 +@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T} + f, v = first(fields), first(values) + if v === nothing && f.required && !f.nullable + _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`") + end + f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key)) + set = v !== nothing || (f.required && f.nullable) + return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) +end + +function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} + _CHECKS[] || return value + _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) + return value +end + +# --- Validation of JSON values against (sub)schemas --- +# +# The generated types enforce most of a schema by themselves. The remaining keywords (`not`, +# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are +# checked by validating the JSON form of a value against the corresponding subschemas, +# which the generator embeds (with their `$ref`s resolved) in the metadata of the types. + +""" + check_formats!(flag::Bool) + +Enable or disable the validation of the `format` keyword. Enabled by default. The formats of +JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`, +`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`, +`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`); +unknown formats are not. +""" +check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag) +const _CHECK_FORMATS = Ref(true) + +const _REGEX_CACHE = Dict{String, Regex}() + +# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without +# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at +# the end, after translating `\s` and long Unicode property names, which PCRE lacks. +const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX | + Base.PCRE.DOLLAR_ENDONLY +_jsregex(p::AbstractString) = + get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p) + +const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" +const _JS_PROPERTIES = Dict( + "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll", + "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M", + "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N", + "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No", + "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd", + "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi", + "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm", + "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z", + "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C", + "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co", + "Unassigned" => "Cn", +) + +function _jsecmaregex(p::AbstractString) + out = IOBuffer() + inclass = false + i = firstindex(p) + while i <= lastindex(p) + c = p[i] + if c == '\\' && i < lastindex(p) + n = p[nextind(p, i)] + j = nextind(p, nextind(p, i)) + if n == 's' + print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]") + elseif n == 'S' && !inclass + print(out, "[^", _JS_SPACES, "]") + elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{' + k = findnext('}', p, j) + k === nothing && (print(out, c, n); i = j; continue) + name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "") + print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}') + j = nextind(p, k) + else + print(out, c, n) + end + i = j + continue + end + # `[]` matches nothing and `[^]` anything, in ECMAScript + if !inclass && startswith(SubString(p, i), "[^]") + print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue + elseif !inclass && startswith(SubString(p, i), "[]") + print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue + end + c == '[' && (inclass = true) + c == ']' && (inclass = false) + print(out, c) + i = nextind(p, i) + end + return String(take!(out)) +end + +# --- Checks of the `format` keyword --- +# +# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not +# `$`, which allows a trailing newline) anchors the patterns. + +_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) + +function _jsdate(s) + m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s) + m === nothing && return false + y, mo, d = parse.(Int, m.captures) + days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) + return 1 <= mo <= 12 && 1 <= d <= days[mo] +end + +function _jstime(s) + m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s) + m === nothing && return false + h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3]) + oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8])) + (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false + if se == 60 + # a leap second is only at 23:59:60 UTC + utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60) + utc == 23 * 60 + 59 || return false + end + return true +end + +function _jsdatetime(s) + m = match(r"^([^Tt]*)[Tt](.*)\z", s) + return m !== nothing && _jsdate(m[1]) && _jstime(m[2]) +end + +function _jsipv4(s) + m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s) + m === nothing && return false + return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures) +end + +function _jsipv6(s) + (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false + parts = split(s, "::") + length(parts) > 2 && return false + groups(p) = isempty(p) ? String[] : split(p, ':') + gs = vcat([groups(p) for p in parts]...) + n = 0 + for (i, g) in enumerate(gs) + if occursin('.', g) + # an IPv4 address can only be the last group + (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false + n += 2 + else + occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false + n += 1 + end + end + return length(parts) == 2 ? n <= 7 : n == 8 +end + +function _jshostname(s) + isascii(s) || return false + s = endswith(s, ".") && length(s) > 1 ? chop(s) : s + (1 <= length(s) <= 253) || return false + for label in split(s, '.') + occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false + # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels + length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false + end + return true +end + +# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the +# IDNA2008 rules are not checked. +const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]") +const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z") + +function _jsidnhostname(s) + s = replace(s, _JS_IDN_DOTS => ".") + (1 <= length(s) <= 253) || return false + occursin(Regex("[\\s\u302E]"), s) && return false + for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.') + (1 <= length(label) <= 63) || return false + (startswith(label, "-") || endswith(label, "-")) && return false + occursin(_JS_IDN_LABEL, label) || return false + occursin(r"^\p{M}", label) && return false + end + return true +end + +const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]" + +function _jsemail(s; idn = false) + i = findlast('@', s) + i === nothing && return false + local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end] + atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT + dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z") + quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" : + r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z" + (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false + if startswith(domain, "[") && endswith(domain, "]") + lit = domain[2:end-1] + return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit) + end + endswith(domain, ".") && return false + return idn ? _jsidnhostname(domain) : _jshostname(domain) +end + +# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority +const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=" +function _jsuri(s; absolute = true, iri = false) + chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]" + occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false + m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s) + m === nothing && return false + absolute && m[1] === nothing && return false + # without a scheme, a first path segment with ':' would be read as a scheme + m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false + for part in (m[3], m[4], m[5]) + part === nothing || !occursin(r"[\[\]]", part) || return false + end + count('#', s) <= 1 || return false + if m[2] !== nothing + auth = m[2] + hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth) + hm === nothing && return false + if startswith(hm[1], "[") + h = hm[1][2:end-1] + (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false + end + end + return true +end + +_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s) +_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s) + +# RFC 6570: literals, and expressions `{[operator]varspec,...}` +const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" * + "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z") +_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s) + +# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months +const _JS_DURATION = let D = "[0-9]+", + time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)", + date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)" + Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z") +end +_jsduration(s) = occursin(_JS_DURATION, s) + +_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s) + +function _jsregexformat(s) + # syntax of PCRE (or Python) that ECMAScript does not have + occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false + try + _jsregex(s) + return true + catch + # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only + # for lookbehinds, which ECMAScript allows with variable width + return occursin("(?<", s) + end +end + +const _FORMATS = Dict{String, Function}( + "date-time" => _jsdatetime, + "date" => _jsdate, + "time" => _jstime, + "duration" => _jsduration, + "email" => _jsemail, + "idn-email" => s -> _jsemail(s; idn = true), + "hostname" => _jshostname, + "idn-hostname" => _jsidnhostname, + "ipv4" => _jsipv4, + "ipv6" => _jsipv6, + "uri" => _jsuri, + "uri-reference" => s -> _jsuri(s; absolute = false), + "iri" => s -> _jsuri(s; iri = true), + "iri-reference" => s -> _jsuri(s; absolute = false, iri = true), + "uri-template" => _jsuritemplate, + "json-pointer" => _jsjsonpointer, + "relative-json-pointer" => _jsreljsonpointer, + "uuid" => _jsuuid, + "regex" => _jsregexformat, +) + +_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) + +function _jstypeok(t::AbstractString, x) + t == "null" && return x === nothing + t == "boolean" && return x isa Bool + t == "integer" && return _jsisinteger(x) + t == "number" && return _jsisnumber(x) + t == "string" && return x isa AbstractString + t == "array" && return x isa AbstractVector + t == "object" && return x isa AbstractDict + return true +end + +function _jsallunique(x) + v = Any[_jsto(el) for el in x] + return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) +end + +""" + _jsvalid(schema, x) -> Union{Nothing, String} + +Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a +message describing the first problem found. +""" +_jsvalid(s, x) = first(_jsvalidann(s, x)) + +# Annotations collected while validating: the properties and array items that were +# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`. +_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items) +_jsbad(msg) = (msg, Set{String}(), Set{Int}()) + +""" + _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items) + +Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the +properties and the (1-based) indices of the items that the schema evaluated, as defined by +JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`. +""" +function _jsvalidann(s, x) + s === true && return _jsok() + s === false && return _jsbad("no value is allowed here") + s isa AbstractDict || return _jsok() + # A value of a generated type (from a field of a generated struct) is valid against + # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through + # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else. + if x isa AbstractSchemaObject + if haskey(s, "\$type") && length(s) == 1 + x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x)) + x = _jsto(x) + elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s)) + x = _jsto(x) + end + end + props = Set{String}() + items = Set{Int}() + addann!(ann) = (union!(props, ann[2]); union!(items, ann[3])) + + if haskey(s, "\$type") + # a generated type: the value must be convertible to it, which checks all of it + T = getfield(@__MODULE__, Symbol(s["\$type"])) + msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing + msg === nothing || return _jsbad(msg) + v = try + _jsfrom(T, x) + catch err + err isa SchemaValidationError || rethrow() + return _jsbad(err.msg) + end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end + x isa AbstractDict && union!(props, String.(keys(x))) + x isa AbstractVector && union!(items, eachindex(x)) + end + + if haskey(s, "type") + ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],) + any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))") + end + haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])") + haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))") + + if _jsisnumber(x) + haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])") + haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])") + haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) && + x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])") + haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) && + x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])") + if haskey(s, "multipleOf") + q = x / s["multipleOf"] + isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])") + end + elseif x isa AbstractString + haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])") + haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])") + haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) && + return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])") + if haskey(s, "format") && _CHECK_FORMATS[] + check = get(_FORMATS, s["format"], nothing) + check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])") + end + elseif x isa AbstractVector + haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items") + haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items") + if get(s, "uniqueItems", false) === true + for i in eachindex(x), j in firstindex(x):i-1 + _jseq(x[i], x[j]) && return _jsbad("items are not unique") + end + end + prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[]) + for (i, sub) in enumerate(prefix) + i <= length(x) || break + err = _jsvalid(sub, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + rest = haskey(s, "prefixItems") ? get(s, "items", nothing) : + get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing) + if rest !== nothing + for i in (length(prefix) + 1):length(x) + err = _jsvalid(rest, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + end + if haskey(s, "contains") + matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing] + n = length(matching) + lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int)) + lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi") + union!(items, matching) + end + elseif x isa AbstractDict + haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties") + haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties") + for k in get(s, "required", ()) + haskey(x, k) || return _jsbad("missing required property `$k`") + end + defined = get(s, "properties", nothing) + patterns = get(s, "patternProperties", nothing) + extra = get(s, "additionalProperties", nothing) + names = get(s, "propertyNames", nothing) + (defined === nothing && patterns === nothing && extra === nothing && names === nothing) || + for (k, v) in x + k = String(k) + matched = false + if defined !== nothing && haskey(defined, k) + matched = true + err = _jsvalid(defined[k], v) + err === nothing || return _jsbad("property `$k`: $err") + end + for (p, sub) in something(patterns, ()) + occursin(_jsregex(p), k) || continue + matched = true + err = _jsvalid(sub, v) + err === nothing || return _jsbad("property `$k`: $err") + end + if !matched && extra !== nothing + err = _jsvalid(extra, v) + err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err") + matched = true + end + matched && push!(props, k) + if names !== nothing + err = _jsvalid(names, k) + err === nothing || return _jsbad("property name `$k`: $err") + end + end + (haskey(s, "dependentRequired") || haskey(s, "dependencies")) && + for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict()))) + haskey(x, k) || continue + for d in deps + haskey(x, d) || return _jsbad("property `$k` requires property `$d`") + end + end + (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) && + for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict()))) + haskey(x, k) || continue + ann = _jsvalidann(sub, x) + ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])") + addann!(ann) + end + end + + for sub in get(s, "allOf", ()) + ann = _jsvalidann(sub, x) + ann[1] === nothing || return ann + addann!(ann) + end + if haskey(s, "anyOf") + anns = [_jsvalidann(sub, x) for sub in s["anyOf"]] + valid = filter(a -> a[1] === nothing, anns) + isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")") + foreach(addann!, valid) + end + if haskey(s, "oneOf") + valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]]) + n = length(valid) + n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" : + "matches $n options of `oneOf`, but must match exactly one") + addann!(only(valid)) + end + haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`") + if haskey(s, "if") + cond = _jsvalidann(s["if"], x) + if cond[1] === nothing + addann!(cond) + if haskey(s, "then") + ann = _jsvalidann(s["then"], x) + ann[1] === nothing || return _jsbad("`then`: " * ann[1]) + addann!(ann) + end + elseif haskey(s, "else") + ann = _jsvalidann(s["else"], x) + ann[1] === nothing || return _jsbad("`else`: " * ann[1]) + addann!(ann) + end + end + + # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this + # schema, or of its valid subschemas, evaluated + if x isa AbstractVector && haskey(s, "unevaluatedItems") + for i in eachindex(x) + i in items && continue + err = _jsvalid(s["unevaluatedItems"], x[i]) + err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err") + push!(items, i) + end + end + if x isa AbstractDict && haskey(s, "unevaluatedProperties") + for (k, v) in x + String(k) in props && continue + err = _jsvalid(s["unevaluatedProperties"], v) + err === nothing || return _jsbad(s["unevaluatedProperties"] === false ? + "property `$k` is not allowed" : "property `$k`: $err") + push!(props, String(k)) + end + end + return (nothing, props, items) +end + +# the JSON names of the properties of a value of a generated type +function _jskeys(x::T) where {T <: AbstractSchemaObject} + spec = _specs(T) + ks = Set{String}() + for f in spec.fields + v = getfield(x, f.name) + (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key) + end + if spec.extra !== nothing + union!(ks, keys(getfield(x, spec.extra))) + end + return ks +end + +# --- Validation of whole values --- + +""" + violations(x) -> Vector{String} + +Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every +value nested in it, against all the constraints of the schema, whether or not the checks +were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per +invalid value (the first problem of each), with its location, e.g. +`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON +names of the properties and 1-based indices of the items: `recipes[1].batch_size`. +""" +function violations(x) + out = String[] + with_checks(true) do + _jscollect!(out, x, Any[]) + if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing + try + _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + catch err + err isa SchemaValidationError || rethrow() + push!(out, err.msg) + end + end + end + return out +end + +""" + validate(x) + +Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing +the problems found, if any. Returns `x`. +""" +validate(x) = _jsvalidateall(x) + +function _jsvalidateall(x) + v = violations(x) + isempty(v) && return x + n = length(v) + _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n " * join(v, "\n ")) +end + +""" + isvalid(x::AbstractSchemaObject) -> Bool + +Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref). +""" +Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x)) + +# The location of a value is kept as a stack of property names and indices, and only +# written out (e.g. `recipes[1].batch_size`) when a problem is found. +function _jsat(path::Vector{Any}, msg) + isempty(path) && return msg + io = IOBuffer() + for (i, p) in enumerate(path) + p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p) + end + return String(take!(io)) * ": " * msg +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} + spec = _vspecs(T) + values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) + extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) + try + _jscheck(T, values, extra) + catch err + err isa SchemaValidationError || rethrow() + push!(out, _jsat(path, err.msg)) + end + _jscollectfields!(out, spec.fields, values, path) + extra === nothing || _jscollect!(out, extra, path) + return out +end + +# (unrolled over the tuples of field metadata and values, as `_jscheckfields`) +@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out +@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path) + v = first(values) + if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} + push!(path, first(fields).key) + _jscollect!(out, v, path) + pop!(path) + end + return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path) +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum} + _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value))) + return out +end +function _jscollect!(out, x::Union{AbstractVector, Tuple}, path) + for (i, v) in enumerate(x) + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, i) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +function _jscollect!(out, x::AbstractDict, path) + for (k, v) in x + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, String(k)) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +_jscollect!(out, x, path) = out + +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall diff --git a/examples/generated/Combined.jl b/examples/generated/Combined.jl index 4259a41..102502a 100644 --- a/examples/generated/Combined.jl +++ b/examples/generated/Combined.jl @@ -5,13 +5,16 @@ module Combined using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export PersonUserTypeEnum, CompanyUserTypeEnum, Person, Company, CombinedSchemaExampleAnyOfIdentifierOption1, CombinedSchemaExampleAnyOfIdentifierOption2 export CombinedSchemaExampleAllOfRequest, CombinedSchemaExample export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -47,52 +50,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -113,6 +80,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -129,18 +100,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -308,36 +267,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -396,7 +663,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -429,17 +696,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -720,7 +976,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -733,13 +988,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -789,12 +1037,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -966,29 +1219,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1003,183 +1233,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1242,7 +1295,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1292,9 +1345,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `combined_schema.json` diff --git a/examples/generated/Enum.jl b/examples/generated/Enum.jl index b470ce4..d4609cf 100644 --- a/examples/generated/Enum.jl +++ b/examples/generated/Enum.jl @@ -5,13 +5,16 @@ module EnumExample using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export ComplexEnumExampleProductShippingStatusEnum, ComplexEnumExampleOrderStatusPriorityEnum, PaymentStatus, ComplexEnumExampleMixedEnumTestEnum, ComplexEnumExampleProduct, ComplexEnumExampleOrderStatus export ComplexEnumExample export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -47,52 +50,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -113,6 +80,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -129,18 +100,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -308,36 +267,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -396,7 +663,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -429,17 +696,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -720,7 +976,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -733,13 +988,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -789,12 +1037,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -966,29 +1219,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1003,183 +1233,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1242,7 +1295,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1292,9 +1345,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `enum_schema.json` diff --git a/examples/generated/Order.jl b/examples/generated/Order.jl index dd5da7a..70b8327 100644 --- a/examples/generated/Order.jl +++ b/examples/generated/Order.jl @@ -5,12 +5,15 @@ module OrderTypes using JSON -export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats! -export validate, violations, checks!, with_checks +export fromjson, tojson, readjson, writejson, fromdict, todict, setfields +export check_formats!, validate, violations, checks!, with_checks export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError export Customer, OrderItemsItem, Order export RootType +# the constructors of the types check the constraints of the schema +const _INLINE_CHECKS = true + # --------------------------------------------------------------------------------------- # Runtime support for generated types. # @@ -46,52 +49,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -112,6 +79,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -128,18 +99,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -307,36 +266,344 @@ function _jsnonnothing(FT) return length(ts) == 1 ? only(ts) : Any end -# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. -function _jsfrom(::Type{T}, x) where {T} - T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") - return _jsfromunion(T, x) -end +# Unions come from `oneOf`/`anyOf`, from lists of types and from optional fields. +function _jsfrom(::Type{T}, x) where {T} + T isa Union || _jsfail("cannot convert $(repr(x)) to `$(_jsname(T))`") + return _jsfromunion(T, x) +end + +function _jsfromunion(::Type{T}, x) where {T} + x isa T && return x + options = Base.uniontypes(T) + x === nothing && Nothing in options && return nothing + # with the checks off, the options are still checked, to choose one + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 + return with_checks(() -> _jsfromunion(T, x), true) + end + msgs = String[] + for S in options + S === Nothing && continue + if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) + msg = _jsmismatch(S, _jsobject(x)) + msg === nothing || (push!(msgs, " `$S`: $msg"); continue) + end + try + return _jsfrom(S, x) + catch err + err isa SchemaValidationError || rethrow() + push!(msgs, " `$S`: $(err.msg)") + end + end + _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +end + +# --- Values of enumerations --- + +# (used to choose an option of a union when reading, and by the checks) +# (strings are compared directly; other values with the equality of JSON values) +function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} + vals = _enumvalues(T) + return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : + any(v -> _jseq(v, value), vals) +end + +_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = + "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" + +_jsisnumber(x) = x isa Real && !(x isa Bool) + +# equality of JSON values: `1 == 1.0`, but `true != 1` +_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : + _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) +_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) +_jseq(a::AbstractDict, b::AbstractDict) = + length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) + +# --- Conversion from Julia values into JSON-compatible values --- + +""" + _jsto(x) + +Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the +original JSON property names (optional fields set to `nothing` are left out, the extra +properties are put back), enums become their values, vectors and tuples become vectors. +The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. +""" +function _jsto end + +_jsto(x) = x +# whole numbers are written without a decimal point, as they usually appear in JSON files +_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x +_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x +# other real numbers (e.g. rationals) are written as floating-point numbers +_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) +_jsto(x::AbstractSchemaEnum) = x.value +_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] +_jsto(x::Tuple) = Any[_jsto(el) for el in x] +_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) + +function _jsto(x::T) where {T <: AbstractSchemaObject} + obj = JSON.Object{String, Any}() + for f in _specs(T).fields + v = getfield(x, f.name) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + spec = _specs(T) + if spec.extra !== nothing + for (k, v) in getfield(x, spec.extra) + obj[k] = _jsto(v) + end + end + return obj +end + +# --- Equality, hashing and display --- + +function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} + return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) +end +function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} + for n in fieldnames(T) + h = hash(getfield(a, n), h) + end + return hash(T, h) +end +Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) +Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) +Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") + +# Structs are shown as calls to their positional constructors, with the numeric types only +# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. +function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} + print(io, nameof(T)) + T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") + print(io, "(") + for (i, n) in enumerate(fieldnames(T)) + i > 1 && print(io, ", ") + show(io, getfield(x, n)) + end + print(io, ")") +end + +# The numeric types of a struct built from positional arguments: those of the generated +# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. +function _jsnumbertypes(args...) + I, F = Int64, Float64 + for a in args + a isa AbstractVector && !isempty(a) && (a = first(a)) + if a isa AbstractSchemaObject + return Tuple(typeof(a).parameters) + elseif a isa Integer && !(a isa Bool) + I = typeof(a) + elseif a isa Real && !(a isa Bool) + F = typeof(a) + end + end + return (I, F) +end +# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` +Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) + +# --- Public API --- + +""" + fromdict(T, x) + +Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, +validating it against the constraints of the schema. +""" +function fromdict(::Type{T}, x) where {T} + value = _jsfrom(T, x) + # the root of the schema may have constraints that its type does not enforce + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + end + return value +end + +""" + todict(x) + +Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). +Optional fields set to `nothing` are omitted. +""" +todict(x) = _jsto(x) + +""" + setfields(x; kwargs...) + +Return a copy of the generated struct `x` with the fields given as keyword arguments +replaced. The new values are converted and validated as by the constructor, so plain values +work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. +Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). + +For nested changes, the generated structs also work with +[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): +`@set recipe.batch_size.value = 40`. +""" +function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} + for k in keys(kwargs) + hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) + end + current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) + return T(; merge(current, values(kwargs))...) +end + +""" + fromjson(T, json::AbstractString) + +Parse the JSON string `json` into a value of type `T`. +""" +function fromjson(::Type{T}, json::AbstractString) where {T} + F = _jsfloattype(T) + # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type + # is asked for: then they are parsed with full precision + return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) +end + +_jsfloattype(::Type) = Float64 +_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = + T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 +_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) + +# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the +# current precision of `BigFloat`), so that they can be converted to any real type. +function _jsparsebig(x) + t = JSON.gettype(x) + if t == JSON.JSONTypes.OBJECT + obj = JSON.Object{String, Any}() + JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) + return obj + elseif t == JSON.JSONTypes.ARRAY + arr = Any[] + JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) + return arr + elseif t == JSON.JSONTypes.NUMBER + v = JSON.parse(x) + return v isa Integer ? v : JSON.parse(x, BigFloat) + end + return JSON.parse(x) +end + +""" + readjson(T, filename) + +Read the JSON file `filename` into a value of type `T`. +""" +readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) + +""" + tojson(x; pretty=false, validate) + +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). +""" +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) + return JSON.json(todict(x); pretty) +end + +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + +""" + writejson(filename, x; pretty=true, validate) + +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. +""" +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) + json = tojson(x; pretty, validate) + open(filename, "w") do io + write(io, json) + pretty && write(io, "\n") + end + return filename +end + +# --------------------------------------------------------------------------------------- +# End of runtime support. Generated types follow. +# --------------------------------------------------------------------------------------- + +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) -function _jsfromunion(::Type{T}, x) where {T} - x isa T && return x - options = Base.uniontypes(T) - x === nothing && Nothing in options && return nothing - # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 - return with_checks(() -> _jsfromunion(T, x), true) - end - msgs = String[] - for S in options - S === Nothing && continue - if S isa DataType && S <: AbstractSchemaObject && (x isa AbstractDict || x isa NamedTuple) - msg = _jsmismatch(S, _jsobject(x)) - msg === nothing || (push!(msgs, " `$S`: $msg"); continue) - end - try - return _jsfrom(S, x) - catch err - err isa SchemaValidationError || rethrow() - push!(msgs, " `$S`: $(err.msg)") - end - end - _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") # --- Validation of constraints --- @@ -395,7 +662,7 @@ constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). """ function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} _CHECKS[] || return nothing - spec = _specs(T) + spec = _vspecs(T) nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) spec.minProperties !== nothing && nprops < spec.minProperties && _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") @@ -428,17 +695,6 @@ end return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) end -# Called by the inner constructors of the generated enum types. -# (strings are compared directly; other values with the equality of JSON values) -function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} - vals = _enumvalues(T) - return value isa AbstractString ? any(v -> v isa AbstractString && v == value, vals) : - any(v -> _jseq(v, value), vals) -end - -_jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = - "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" - function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} _CHECKS[] || return value _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) @@ -719,7 +975,6 @@ const _FORMATS = Dict{String, Function}( ) _jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) -_jsisnumber(x) = x isa Real && !(x isa Bool) function _jstypeok(t::AbstractString, x) t == "null" && return x === nothing @@ -732,13 +987,6 @@ function _jstypeok(t::AbstractString, x) return true end -# equality of JSON values: `1 == 1.0`, but `true != 1` -_jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : - _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) -_jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jseq(x, y) for (x, y) in zip(a, b)) -_jseq(a::AbstractDict, b::AbstractDict) = - length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) - function _jsallunique(x) v = Any[_jsto(el) for el in x] return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) @@ -788,12 +1036,17 @@ function _jsvalidann(s, x) T = getfield(@__MODULE__, Symbol(s["\$type"])) msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing msg === nothing || return _jsbad(msg) - try + v = try _jsfrom(T, x) catch err err isa SchemaValidationError || rethrow() return _jsbad(err.msg) end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end x isa AbstractDict && union!(props, String.(keys(x))) x isa AbstractVector && union!(items, eachindex(x)) end @@ -965,29 +1218,6 @@ function _jsvalidann(s, x) return (nothing, props, items) end -# --- Conversion from Julia values into JSON-compatible values --- - -""" - _jsto(x) - -Convert `x` into a JSON-compatible value ("to JSON"): structs become `JSON.Object`s with the -original JSON property names (optional fields set to `nothing` are left out, the extra -properties are put back), enums become their values, vectors and tuples become vectors. -The inverse of [`_jsfrom`](@ref); used by `todict`, `tojson` and `writejson`. -""" -function _jsto end - -_jsto(x) = x -# whole numbers are written without a decimal point, as they usually appear in JSON files -_jsto(x::Float64) = isinteger(x) && abs(x) < 2.0^53 ? Int64(x) : x -_jsto(x::AbstractFloat) = isfinite(x) && isinteger(x) ? BigInt(x) : x -# other real numbers (e.g. rationals) are written as floating-point numbers -_jsto(x::Real) = x isa Integer ? x : _jsto(BigFloat(x)) -_jsto(x::AbstractSchemaEnum) = x.value -_jsto(x::AbstractVector) = Any[_jsto(el) for el in x] -_jsto(x::Tuple) = Any[_jsto(el) for el in x] -_jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) - # the JSON names of the properties of a value of a generated type function _jskeys(x::T) where {T <: AbstractSchemaObject} spec = _specs(T) @@ -1002,183 +1232,6 @@ function _jskeys(x::T) where {T <: AbstractSchemaObject} return ks end -function _jsto(x::T) where {T <: AbstractSchemaObject} - obj = JSON.Object{String, Any}() - for f in _specs(T).fields - v = getfield(x, f.name) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - spec = _specs(T) - if spec.extra !== nothing - for (k, v) in getfield(x, spec.extra) - obj[k] = _jsto(v) - end - end - return obj -end - -# --- Equality, hashing and display --- - -function Base.:(==)(a::T, b::T) where {T <: AbstractSchemaObject} - return all(getfield(a, n) == getfield(b, n) for n in fieldnames(T)) -end -function Base.hash(a::T, h::UInt) where {T <: AbstractSchemaObject} - for n in fieldnames(T) - h = hash(getfield(a, n), h) - end - return hash(T, h) -end -Base.:(==)(a::T, b::T) where {T <: AbstractSchemaEnum} = isequal(a.value, b.value) -Base.hash(a::AbstractSchemaEnum, h::UInt) = hash(a.value, hash(typeof(a), h)) -Base.show(io::IO, x::AbstractSchemaEnum) = print(io, nameof(typeof(x)), "(", repr(x.value), ")") - -# Structs are shown as calls to their positional constructors, with the numeric types only -# when they are not the default ones, e.g. `VolumeType(VolumeUnitType("l"), 20.0)`. -function Base.show(io::IO, x::T) where {T <: AbstractSchemaObject} - print(io, nameof(T)) - T.parameters == Core.svec(Int64, Float64) || print(io, "{", join(T.parameters, ", "), "}") - print(io, "(") - for (i, n) in enumerate(fieldnames(T)) - i > 1 && print(io, ", ") - show(io, getfield(x, n)) - end - print(io, ")") -end - -# The numeric types of a struct built from positional arguments: those of the generated -# structs, or of the numbers, among the arguments; by default, `Int64` and `Float64`. -function _jsnumbertypes(args...) - I, F = Int64, Float64 - for a in args - a isa AbstractVector && !isempty(a) && (a = first(a)) - if a isa AbstractSchemaObject - return Tuple(typeof(a).parameters) - elseif a isa Integer && !(a isa Bool) - I = typeof(a) - elseif a isa Real && !(a isa Bool) - F = typeof(a) - end - end - return (I, F) -end -# `print` and `string` give the plain value, e.g. `"$(VolumeUnitType("l"))" == "l"` -Base.print(io::IO, x::AbstractSchemaEnum) = print(io, x.value) - -# --- Public API --- - -""" - fromdict(T, x) - -Convert a parsed JSON value `x` (e.g. a `Dict` or a `JSON.Object`) into a value of type `T`, -validating it against the constraints of the schema. -""" -function fromdict(::Type{T}, x) where {T} - value = _jsfrom(T, x) - # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing - _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - end - return value -end - -""" - todict(x) - -Convert `x` into a JSON-compatible value (nested `JSON.Object`s, vectors and scalars). -Optional fields set to `nothing` are omitted. -""" -todict(x) = _jsto(x) - -""" - setfields(x; kwargs...) - -Return a copy of the generated struct `x` with the fields given as keyword arguments -replaced. The new values are converted and validated as by the constructor, so plain values -work: `setfields(volume; value = 40)`, `setfields(recipe; batch_size = (unit = "l", value = 40))`. -Use the Julia names of the fields (e.g. `first_name` for a JSON property `first-name`). - -For nested changes, the generated structs also work with -[Accessors.jl](https://github.com/JuliaObjects/Accessors.jl): -`@set recipe.batch_size.value = 40`. -""" -function setfields(x::T; kwargs...) where {T <: AbstractSchemaObject} - for k in keys(kwargs) - hasfield(T, k) || throw(ArgumentError("`$(_jsname(T))` has no field `$k`")) - end - current = NamedTuple{fieldnames(T)}(ntuple(i -> getfield(x, i), Val(fieldcount(T)))) - return T(; merge(current, values(kwargs))...) -end - -""" - fromjson(T, json::AbstractString) - -Parse the JSON string `json` into a value of type `T`. -""" -function fromjson(::Type{T}, json::AbstractString) where {T} - F = _jsfloattype(T) - # numbers are parsed as `Float64` by JSON.jl, except when another floating-point type - # is asked for: then they are parsed with full precision - return fromdict(T, F === Float64 ? JSON.parse(json) : _jsparsebig(JSON.lazy(json))) -end - -_jsfloattype(::Type) = Float64 -_jsfloattype(::Type{T}) where {T <: AbstractSchemaObject} = - T isa DataType && length(T.parameters) == 2 ? T.parameters[2] : Float64 -_jsfloattype(::Type{Vector{T}}) where {T} = _jsfloattype(T) - -# Materialize a lazily parsed JSON value, parsing non-integer numbers as `BigFloat` (at the -# current precision of `BigFloat`), so that they can be converted to any real type. -function _jsparsebig(x) - t = JSON.gettype(x) - if t == JSON.JSONTypes.OBJECT - obj = JSON.Object{String, Any}() - JSON.applyobject((k, v) -> (obj[String(k)] = _jsparsebig(v); nothing), x) - return obj - elseif t == JSON.JSONTypes.ARRAY - arr = Any[] - JSON.applyarray((i, v) -> (push!(arr, _jsparsebig(v)); nothing), x) - return arr - elseif t == JSON.JSONTypes.NUMBER - v = JSON.parse(x) - return v isa Integer ? v : JSON.parse(x, BigFloat) - end - return JSON.parse(x) -end - -""" - readjson(T, filename) - -Read the JSON file `filename` into a value of type `T`. -""" -readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) - -""" - tojson(x; pretty=false, validate=!checks()) - -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) - return JSON.json(todict(x); pretty) -end - -""" - writejson(filename, x; pretty=true, validate=!checks()) - -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). -""" -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) - json = tojson(x; pretty, validate) - open(filename, "w") do io - write(io, json) - pretty && write(io, "\n") - end - return filename -end - # --- Validation of whole values --- """ @@ -1241,7 +1294,7 @@ function _jsat(path::Vector{Any}, msg) end function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) + spec = _vspecs(T) values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) try @@ -1291,9 +1344,8 @@ function _jscollect!(out, x::AbstractDict, path) end _jscollect!(out, x, path) = out -# --------------------------------------------------------------------------------------- -# End of runtime support. Generated types follow. -# --------------------------------------------------------------------------------------- +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall # --------------------------------------------------------------------------------------- # Types from `customer_schema.json` diff --git a/src/generator.jl b/src/generator.jl index 8075f7b..68df34b 100644 --- a/src/generator.jl +++ b/src/generator.jl @@ -5,6 +5,9 @@ const RUNTIME_FILE = joinpath(@__DIR__, "runtime.jl") include_dependency(RUNTIME_FILE) const RUNTIME_CODE = read(RUNTIME_FILE, String) +const VALIDATION_FILE = joinpath(@__DIR__, "runtime_validation.jl") +include_dependency(VALIDATION_FILE) +const VALIDATION_CODE = read(VALIDATION_FILE, String) const FORMATS_FILE = joinpath(@__DIR__, "runtime_formats.jl") include_dependency(FORMATS_FILE) const FORMATS_CODE = read(FORMATS_FILE, String) @@ -107,6 +110,7 @@ mutable struct Generator used_formats::Bool # whether any typed format was used use_defaults::Bool # optional fields default to the schema `default` checks::Bool # the checks of the constraints are on by default + validation::Symbol # `:inline`, `:separate` or `:none` types::Dict{String, Union{ObjectDef, EnumDef}} # location => definition names::Dict{String, String} # location => type name taken::Dict{String, String} # type name => location @@ -117,7 +121,7 @@ end Generator(root_file::String, root_name::String) = Generator( root_file, root_name, Dict{String, Any}(), Dict{String, Tuple{String, String}}(), - Dict{String, Vector{Pair{String, String}}}(), Dict{String, String}(), nothing, false, false, false, true, + Dict{String, Vector{Pair{String, String}}}(), Dict{String, String}(), nothing, false, false, false, true, :inline, Dict{String, Union{ObjectDef, EnumDef}}(), Dict{String, String}(), Dict{String, String}(), String[], Dict{String, String}(), Set{String}(), @@ -1275,7 +1279,7 @@ function constraints_literal(c) return "(" * join(parts, ", ") * ",)" end -function emit_enum(io::IO, d::EnumDef) +function emit_enum(io::IO, d::EnumDef, inline::Bool = true) println(io, "\"\"\"") println(io, " ", d.name, "(value)") println(io) @@ -1284,7 +1288,11 @@ function emit_enum(io::IO, d::EnumDef) println(io, "\"\"\"") println(io, "struct ", d.name, " <: AbstractSchemaEnum") println(io, " value::", d.valuetype) - println(io, " ", d.name, "(value) = new(_jscheckenum(", d.name, ", _jsfrom(", d.valuetype, ", value)))") + if inline + println(io, " ", d.name, "(value) = new(_jscheckenum(", d.name, ", _jsfrom(", d.valuetype, ", value)))") + else + println(io, " ", d.name, "(value) = new(_jsfrom(", d.valuetype, ", value))") + end println(io, "end") # the allowed values, as a constant tuple (fast to check), also recorded in `_SPECS` println(io, "const _VALUES_", d.name, " = (", join(julia_literal.(d.values), ", "), length(d.values) == 1 ? ",)" : ")") @@ -1293,7 +1301,7 @@ function emit_enum(io::IO, d::EnumDef) println(io) end -function emit_struct(io::IO, d::ObjectDef, defined::Set{String}) +function emit_struct(io::IO, d::ObjectDef, defined::Set{String}, inline::Bool = true, vio::Union{Nothing, IO} = nothing) # The type parameters are named `I` and `T`, unless the struct is named so or uses a type # named so; in the constructors, whose arguments are named after the fields, they must # not clash with the field names either. @@ -1368,8 +1376,8 @@ function emit_struct(io::IO, d::ObjectDef, defined::Set{String}) end extra === nothing || println(io, " ", extra, " = _jsfrom(Dict{String, ", sub(d.extra_type.expr), "}, ", extra, ")") vals = join([f.name for f in d.fields], ", ") - println(io, " _jscheck(", self, "{$pI, $pT}, (", vals, isempty(d.fields) || length(d.fields) > 1 ? "" : ",", "), ", - something(extra, "nothing"), ")") + inline && println(io, " _jscheck(", self, "{$pI, $pT}, (", vals, isempty(d.fields) || length(d.fields) > 1 ? "" : ",", "), ", + something(extra, "nothing"), ")") println(io, " return new(", join(vcat([f.name for f in d.fields], extra === nothing ? String[] : [extra]), ", "), ")") println(io, " end") println(io, "end") @@ -1387,27 +1395,43 @@ function emit_struct(io::IO, d::ObjectDef, defined::Set{String}) # metadata # (a constant, returned by a method specialized on the type, so the checks are type-stable) - println(io, "const _SPEC_", d.name, " = (") + # (without the checks in the constructors, only what reading and writing need; all of it + # goes in the validation file, if any) + emit_spec(io, d, "_SPEC_", inline) + println(io, "_specs(::Type{<:", d.name, "}) = _SPEC_", d.name) + println(io, "_SPECS[", d.name, "] = _SPEC_", d.name) + println(io) + if vio !== nothing + emit_spec(vio, d, "_VSPEC_", true) + println(vio, "_vspecs(::Type{<:", d.name, "}) = _VSPEC_", d.name) + println(vio) + end +end + +function emit_spec(io::IO, d::ObjectDef, prefix::String, full::Bool) + extra = d.extra_field + println(io, "const ", prefix, d.name, " = (") println(io, " fields = (") for f in d.fields - println(io, " (name = :", f.name, ", key = ", repr(f.key), ", required = ", f.required, - ", nullable = ", f.nullable, ", constraints = ", constraints_literal(f.constraints), "),") + print(io, " (name = :", f.name, ", key = ", repr(f.key), ", required = ", f.required, + ", nullable = ", f.nullable) + full && print(io, ", constraints = ", constraints_literal(f.constraints)) + println(io, "),") end println(io, " ),") - println(io, " additionalProperties = ", d.additional_properties, ",") + full && println(io, " additionalProperties = ", d.additional_properties, ",") println(io, " extra = ", extra === nothing ? "nothing" : ":" * extra, ",") - println(io, " minProperties = ", something(d.min_properties, "nothing"), ",") - println(io, " maxProperties = ", something(d.max_properties, "nothing"), ",") - println(io, " schema = ", schema_literal(d.schema, " "), ",") + if full + println(io, " minProperties = ", something(d.min_properties, "nothing"), ",") + println(io, " maxProperties = ", something(d.max_properties, "nothing"), ",") + println(io, " schema = ", schema_literal(d.schema, " "), ",") + end println(io, ")") - println(io, "_specs(::Type{<:", d.name, "}) = _SPEC_", d.name) - println(io, "_SPECS[", d.name, "] = _SPEC_", d.name) - println(io) end """ generate_module(schema_file, output; root_name, module_name, schemas, split, type_names, - download, typed_formats, use_defaults, checks) -> String + download, typed_formats, use_defaults, checks, validation) -> String Read the JSON Schema in `schema_file` (and every schema file it references through `\$ref`) and write to `output_file` a Julia module defining types for all the objects and @@ -1438,6 +1462,15 @@ turned off, for speed: values are only converted to the types of their fields, a by `validate(x)`, and by `tojson` and `writejson` before writing. The checks can be turned on and off at any time with `checks!(flag)` and `with_checks(f, flag)`. +With `validation = :separate`, the types are minimal: their constructors only convert the +values to the types of their fields, without checking the constraints of the schema, and +the code for checking them (the constraints of each type, and the validator) is written +to a separate file, `validation.jl` (or `_validation.jl` next to `output`, without +`split`), which the module includes only if it is present. It provides `validate(x)`, +`violations(x)` and `isvalid(x)`, and makes `tojson` and `writejson` validate before +writing. With `validation = :none`, that file is not written. The default, +`validation = :inline`, puts the checks in the constructors. + The name of the root type is `root_name`, which defaults to the `title` of the schema or else to the name of the schema file. The module name defaults to the root type name followed by `Types`. @@ -1468,12 +1501,18 @@ function generate_module( typed_formats::Bool = false, use_defaults::Bool = false, checks::Bool = true, + validation::Symbol = :inline, ) root_file = abspath(normpath(schema_file)) gen = Generator(root_file, "") gen.typed_formats = typed_formats gen.use_defaults = use_defaults + validation in (:inline, :separate, :none) || + throw(ArgumentError("`validation` must be `:inline`, `:separate` or `:none`, got `:$validation`")) + checks || validation === :inline || + throw(ArgumentError("`checks = false` only applies with `validation = :inline`")) gen.checks = checks + gen.validation = validation gen.fetch = download === true ? download_schema : download === false ? nothing : download for (k, v) in type_names key = startswith(k, "#") ? basename(root_file) * k : String(k) @@ -1503,7 +1542,9 @@ function generate_module( @warn "`type_names` entry `$k` does not name a generated type; it was ignored" end - files = generate_files(gen, module_name, root_type, basename(schema_file), split; root_constraints) + validation_file = split ? "validation.jl" : splitext(basename(output_file))[1] * "_validation.jl" + files = generate_files(gen, module_name, root_type, basename(schema_file), split; + root_constraints, validation_file) if split mkpath(output_file) for (name, code) in files @@ -1512,7 +1553,10 @@ function generate_module( return joinpath(output_file, first(first(files))) end mkpath(dirname(abspath(output_file))) - write(output_file, only(files)[2]) + write(output_file, first(files)[2]) + for (name, code) in files[2:end] # the validation file, with `validation = :separate` + write(joinpath(dirname(abspath(output_file)), name), code) + end return output_file end @@ -1525,7 +1569,8 @@ Generate the code of the module, as a list of `filename => code`, the main file Without `split`, everything goes into the single main file. """ function generate_files(gen::Generator, module_name::String, root_type::TypeRef, - schema_name::String, split::Bool; root_constraints = nothing) + schema_name::String, split::Bool; root_constraints = nothing, + validation_file::String = "validation.jl") groups = group_types(gen) names = [d.name for (_, ds) in groups for d in ds] if module_name in names @@ -1534,23 +1579,28 @@ function generate_files(gen::Generator, module_name::String, root_type::TypeRef, "type; choose another `module_name` (e.g. `$(module_name)Types`)")) end main_file = module_name * ".jl" + inline = gen.validation === :inline + separate = gen.validation === :separate + reserved = (main_file, "runtime.jl", "runtime_formats.jl", "runtime_validation.jl", validation_file) - # code of each group + # code of each group, and the metadata for the validation file, if any defined = Set{String}() group_code = Pair{String, String}[] + vio = separate ? IOBuffer() : nothing for (group, defs) in groups io = IOBuffer() for d in defs - d isa EnumDef ? emit_enum(io, d) : emit_struct(io, d, defined) + d isa EnumDef ? emit_enum(io, d, inline) : emit_struct(io, d, defined, inline, vio) push!(defined, d.name) end filename = group * ".jl" - while filename in (main_file, "runtime.jl", "runtime_formats.jl") || any(p -> p[1] == filename, group_code) + while filename in reserved || any(p -> p[1] == filename, group_code) filename = splitext(filename)[1] * "_types.jl" end push!(group_code, filename => String(take!(io))) end sources(group) = join(["`$(basename(f))`" for f in unique(schema_file_of.(last(groups[group])))], ", ") + root_line = root_constraints === nothing ? nothing : "_ROOT_CONSTRAINTS[] = " * constraints_literal(root_constraints) io = IOBuffer() println(io, "# This file was generated by JSONSchema2Types.jl from the JSON Schema") @@ -1560,16 +1610,25 @@ function generate_files(gen::Generator, module_name::String, root_type::TypeRef, println(io) println(io, "using JSON") println(io) - println(io, "export fromjson, tojson, readjson, writejson, fromdict, todict, setfields, check_formats!") - println(io, "export validate, violations, checks!, with_checks") + println(io, "export fromjson, tojson, readjson, writejson, fromdict, todict, setfields") + inline && println(io, "export check_formats!, validate, violations, checks!, with_checks") println(io, "export AbstractSchemaObject, AbstractSchemaEnum, SchemaValidationError") for chunk in Iterators.partition(names, 6) println(io, "export ", join(chunk, ", ")) end println(io, "export RootType") println(io) + if inline + println(io, "# the constructors of the types check the constraints of the schema") + else + println(io, "# the constructors of the types do not check the constraints of the schema (generated") + println(io, "# with `validation = :", gen.validation, "`)") + end + println(io, "const _INLINE_CHECKS = ", inline) + println(io) if split println(io, "include(\"runtime.jl\")") + inline && println(io, "include(\"runtime_validation.jl\")") gen.used_formats && println(io, "include(\"runtime_formats.jl\")") println(io) println(io, "# Generated types, one file per schema file, in dependency order") @@ -1578,6 +1637,7 @@ function generate_files(gen::Generator, module_name::String, root_type::TypeRef, end else print(io, RUNTIME_CODE) + inline && (println(io); print(io, VALIDATION_CODE)) gen.used_formats && (println(io); print(io, FORMATS_CODE)) for (i, (_, code)) in enumerate(group_code) println(io) @@ -1600,28 +1660,44 @@ function generate_files(gen::Generator, module_name::String, root_type::TypeRef, end println(io, "\"\"\"") println(io, "const RootType = ", root_expr) - if root_constraints !== nothing + if inline && root_line !== nothing println(io) println(io, "# constraints on the root of the schema, checked when reading a document") - println(io, "_ROOT_CONSTRAINTS[] = ", constraints_literal(root_constraints)) + println(io, root_line) end - if !gen.checks + if inline && !gen.checks println(io) println(io, "# generated with `checks = false`: the constraints of the schema are checked by") println(io, "# `validate` (and when writing), not when values are created; see `checks!`") println(io, "checks!(false)") end + if separate + println(io) + println(io, "# The checks of the constraints of the schema, by `validate`, `violations` and `isvalid`,") + println(io, "# and before writing. Optional: without the file `", validation_file, "`, the module only") + println(io, "# reads and writes.") + println(io, "isfile(joinpath(@__DIR__, ", repr(validation_file), ")) && include(", repr(validation_file), ")") + end println(io) println(io, "end # module ", module_name) files = [main_file => String(take!(io))] - split || return files included = "# This file is included by `$main_file`, generated by JSONSchema2Types.jl from the JSON\n" * "# Schema `$schema_name`. $GENERATED_NOTICE\n" - push!(files, "runtime.jl" => included * "\n" * RUNTIME_CODE) - gen.used_formats && push!(files, "runtime_formats.jl" => included * "\n" * FORMATS_CODE) - for (i, (filename, code)) in enumerate(group_code) - push!(files, filename => included * "#\n# Types from " * sources(i) * ".\n\n" * code) + if split + push!(files, "runtime.jl" => included * "\n" * RUNTIME_CODE) + inline && push!(files, "runtime_validation.jl" => included * "\n" * VALIDATION_CODE) + gen.used_formats && push!(files, "runtime_formats.jl" => included * "\n" * FORMATS_CODE) + for (i, (filename, code)) in enumerate(group_code) + push!(files, filename => included * "#\n# Types from " * sources(i) * ".\n\n" * code) + end + end + if separate + vcode = included * "#\n# The checks of the constraints of the schema: optional, see the end of `$main_file`.\n\n" * + "export validate, violations, check_formats!\n\n" * VALIDATION_CODE * + "\n# Metadata of the types, with their constraints\n\n" * String(take!(vio)) * + (root_line === nothing ? "" : "# constraints on the root of the schema\n" * root_line * "\n") + push!(files, validation_file => vcode) end return files end diff --git a/src/runtime.jl b/src/runtime.jl index 04077f0..5c10dea 100644 --- a/src/runtime.jl +++ b/src/runtime.jl @@ -33,52 +33,16 @@ Base.showerror(io::IO, e::SchemaValidationError) = print(io, "SchemaValidationEr _jsfail(msg) = throw(SchemaValidationError(msg)) -# --- Turning the checks off --- +# --- Checks --- +# +# `_INLINE_CHECKS` is a constant defined by the generated module, before this code: `true` +# when the constructors of the generated types check the constraints of the schema +# (`validation = :inline`), `false` when they only convert the values to the types of their +# fields (`validation = :separate` or `:none`). The validation code (`runtime_validation.jl`), +# when present, sets `_VALIDATOR`, which `tojson` and `writejson` use. const _CHECKS = Ref(true) - -""" - checks!(flag::Bool) - -Turn on or off the checks of the constraints of the schema when values of the generated -types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). -They are on by default (unless the module was generated with `checks = false`). - -With the checks off, values are only converted to the types of their fields, which still -enforce the structure of the schema (the types of the properties, required properties, -the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, -the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later -with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the -checks are off. A JSON value read into a union of generated types (from `oneOf` or -`anyOf`) is still checked, to choose its type. - -The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it -temporarily. Returns the previous setting. -""" -checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) - -""" - checks() -> Bool - -Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). -""" -checks() = _CHECKS[] - -""" - with_checks(f, flag::Bool) - -Call `f()` with the checks of the constraints of the schema turned on or off (see -[`checks!`](@ref)), and restore the previous setting afterwards: -`with_checks(false) do ... end`. -""" -function with_checks(f, flag::Bool) - old = checks!(flag) - try - return f() - finally - _CHECKS[] = old - end -end +const _VALIDATOR = Ref{Any}(nothing) # name of a type for messages, without the module, e.g. `VolumeType` or `Union{A, B}` _jsname(T) = T isa Union ? "Union{" * join(map(_jsname, Base.uniontypes(T)), ", ") * "}" : @@ -99,6 +63,10 @@ Metadata of the generated types, filled in right after each type definition. For * `minProperties`, `maxProperties`, and `schema`, the subschema checked on the object as a whole at runtime (or `nothing`). +In modules generated with `validation = :separate` or `:none`, it only has what reading and +writing need: the `name`, `key`, `required` and `nullable` of the fields, and `extra`; the +validation file then defines `_vspecs` for each struct, with all of it. + For an enum type, `_SPECS[T]` holds the allowed `values`. """ const _SPECS = Dict{Any, Any}() @@ -115,18 +83,6 @@ _specs(::Type{T}) where {T <: AbstractSchemaObject} = _SPECS[Base.typename(T).wr # Metadata of each generated enum type: the allowed values. _enumvalues(::Type{T}) where {T <: AbstractSchemaEnum} = _SPECS[T].values -# Where a value is in a document, for the messages of the errors: built only when a check -# fails, so that valid values cost no string allocations. -struct _JSField{T} - key::String -end -Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") -struct _JSItem{W} - parent::W - index::Int -end -Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") - # --- Conversion from parsed JSON values into Julia values --- """ @@ -305,7 +261,7 @@ function _jsfromunion(::Type{T}, x) where {T} options = Base.uniontypes(T) x === nothing && Nothing in options && return nothing # with the checks off, the options are still checked, to choose one - if !_CHECKS[] && count(!=(Nothing), options) > 1 + if _INLINE_CHECKS && !_CHECKS[] && count(!=(Nothing), options) > 1 return with_checks(() -> _jsfromunion(T, x), true) end msgs = String[] @@ -325,97 +281,9 @@ function _jsfromunion(::Type{T}, x) where {T} _jsfail("value does not match any of the options of `$(_jsname(T))`:\n" * join(msgs, "\n")) end -# --- Validation of constraints --- - -_jslength(x::AbstractString) = length(x) - -# values of typed formats (dates, UUIDs) are validated through their string form -_jsscalar(x) = x - -# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`) -function _jsvalidate(x, c, where_; null_is_value::Bool = false) - c === nothing && return nothing - x === nothing && !null_is_value && return nothing - x = _jsscalar(x) - if haskey(c, :schema) - err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x)) - err === nothing || _jsfail("$where_ is invalid: $err") - end - if x isa Real && !(x isa Bool) - haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x") - haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x") - haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x") - haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x") - if haskey(c, :multipleOf) - q = x / c.multipleOf - isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x") - end - elseif x isa AbstractString - haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))") - haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))") - haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))") - elseif x isa AbstractVector - haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))") - haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))") - haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items") - if haskey(c, :items) - for (i, el) in enumerate(x) - _jsvalidate(el, c.items, _JSItem(where_, i)) - end - end - elseif x isa AbstractDict - haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties") - haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties") - end - return nothing -end - -""" - _jscheck(T, values, extra) - -Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the -converted field `values` and the additional properties `extra`. Called by the inner -constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that -required fields are set, the constraints of each field (`minimum`, `pattern`, -`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the -constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). -""" -function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} - _CHECKS[] || return nothing - spec = _specs(T) - nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) - spec.minProperties !== nothing && nprops < spec.minProperties && - _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") - spec.maxProperties !== nothing && nprops > spec.maxProperties && - _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops") - if spec.schema !== nothing - # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...) - obj = JSON.Object{String, Any}() - for (f, v) in zip(spec.fields, values) - v === nothing && !(f.required && f.nullable) && continue - obj[f.key] = _jsto(v) - end - extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra) - err = _jsvalid(spec.schema, obj) - err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err") - end - return nothing -end - -# The checks of the fields, unrolled over the tuples of field metadata and values (the -# metadata is a constant, so this is type-stable); returns the number of properties set. -@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0 -@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T} - f, v = first(fields), first(values) - if v === nothing && f.required && !f.nullable - _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`") - end - f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key)) - set = v !== nothing || (f.required && f.nullable) - return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) -end +# --- Values of enumerations --- -# Called by the inner constructors of the generated enum types. +# (used to choose an option of a union when reading, and by the checks) # (strings are compared directly; other values with the equality of JSON values) function _jsenumok(::Type{T}, value) where {T <: AbstractSchemaEnum} vals = _enumvalues(T) @@ -426,299 +294,8 @@ end _jsenummsg(::Type{T}, value) where {T <: AbstractSchemaEnum} = "invalid value $(repr(value)) for `$(_jsname(T))`; allowed values are $(join(repr.(_enumvalues(T)), ", "))" -function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} - _CHECKS[] || return value - _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) - return value -end - -# --- Validation of JSON values against (sub)schemas --- -# -# The generated types enforce most of a schema by themselves. The remaining keywords (`not`, -# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are -# checked by validating the JSON form of a value against the corresponding subschemas, -# which the generator embeds (with their `$ref`s resolved) in the metadata of the types. - -""" - check_formats!(flag::Bool) - -Enable or disable the validation of the `format` keyword. Enabled by default. The formats of -JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`, -`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`, -`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`); -unknown formats are not. -""" -check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag) -const _CHECK_FORMATS = Ref(true) - -const _REGEX_CACHE = Dict{String, Regex}() - -# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without -# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at -# the end, after translating `\s` and long Unicode property names, which PCRE lacks. -const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX | - Base.PCRE.DOLLAR_ENDONLY -_jsregex(p::AbstractString) = - get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p) - -const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" -const _JS_PROPERTIES = Dict( - "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll", - "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M", - "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N", - "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No", - "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd", - "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi", - "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm", - "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z", - "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C", - "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co", - "Unassigned" => "Cn", -) - -function _jsecmaregex(p::AbstractString) - out = IOBuffer() - inclass = false - i = firstindex(p) - while i <= lastindex(p) - c = p[i] - if c == '\\' && i < lastindex(p) - n = p[nextind(p, i)] - j = nextind(p, nextind(p, i)) - if n == 's' - print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]") - elseif n == 'S' && !inclass - print(out, "[^", _JS_SPACES, "]") - elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{' - k = findnext('}', p, j) - k === nothing && (print(out, c, n); i = j; continue) - name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "") - print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}') - j = nextind(p, k) - else - print(out, c, n) - end - i = j - continue - end - # `[]` matches nothing and `[^]` anything, in ECMAScript - if !inclass && startswith(SubString(p, i), "[^]") - print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue - elseif !inclass && startswith(SubString(p, i), "[]") - print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue - end - c == '[' && (inclass = true) - c == ']' && (inclass = false) - print(out, c) - i = nextind(p, i) - end - return String(take!(out)) -end - -# --- Checks of the `format` keyword --- -# -# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not -# `$`, which allows a trailing newline) anchors the patterns. - -_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) - -function _jsdate(s) - m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s) - m === nothing && return false - y, mo, d = parse.(Int, m.captures) - days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) - return 1 <= mo <= 12 && 1 <= d <= days[mo] -end - -function _jstime(s) - m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s) - m === nothing && return false - h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3]) - oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8])) - (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false - if se == 60 - # a leap second is only at 23:59:60 UTC - utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60) - utc == 23 * 60 + 59 || return false - end - return true -end - -function _jsdatetime(s) - m = match(r"^([^Tt]*)[Tt](.*)\z", s) - return m !== nothing && _jsdate(m[1]) && _jstime(m[2]) -end - -function _jsipv4(s) - m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s) - m === nothing && return false - return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures) -end - -function _jsipv6(s) - (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false - parts = split(s, "::") - length(parts) > 2 && return false - groups(p) = isempty(p) ? String[] : split(p, ':') - gs = vcat([groups(p) for p in parts]...) - n = 0 - for (i, g) in enumerate(gs) - if occursin('.', g) - # an IPv4 address can only be the last group - (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false - n += 2 - else - occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false - n += 1 - end - end - return length(parts) == 2 ? n <= 7 : n == 8 -end - -function _jshostname(s) - isascii(s) || return false - s = endswith(s, ".") && length(s) > 1 ? chop(s) : s - (1 <= length(s) <= 253) || return false - for label in split(s, '.') - occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false - # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels - length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false - end - return true -end - -# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the -# IDNA2008 rules are not checked. -const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]") -const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z") - -function _jsidnhostname(s) - s = replace(s, _JS_IDN_DOTS => ".") - (1 <= length(s) <= 253) || return false - occursin(Regex("[\\s\u302E]"), s) && return false - for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.') - (1 <= length(label) <= 63) || return false - (startswith(label, "-") || endswith(label, "-")) && return false - occursin(_JS_IDN_LABEL, label) || return false - occursin(r"^\p{M}", label) && return false - end - return true -end - -const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]" - -function _jsemail(s; idn = false) - i = findlast('@', s) - i === nothing && return false - local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end] - atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT - dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z") - quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" : - r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z" - (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false - if startswith(domain, "[") && endswith(domain, "]") - lit = domain[2:end-1] - return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit) - end - endswith(domain, ".") && return false - return idn ? _jsidnhostname(domain) : _jshostname(domain) -end - -# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority -const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=" -function _jsuri(s; absolute = true, iri = false) - chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]" - occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false - m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s) - m === nothing && return false - absolute && m[1] === nothing && return false - # without a scheme, a first path segment with ':' would be read as a scheme - m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false - for part in (m[3], m[4], m[5]) - part === nothing || !occursin(r"[\[\]]", part) || return false - end - count('#', s) <= 1 || return false - if m[2] !== nothing - auth = m[2] - hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth) - hm === nothing && return false - if startswith(hm[1], "[") - h = hm[1][2:end-1] - (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false - end - end - return true -end - -_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s) -_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s) - -# RFC 6570: literals, and expressions `{[operator]varspec,...}` -const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" * - "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * - "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * - "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z") -_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s) - -# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months -const _JS_DURATION = let D = "[0-9]+", - time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)", - date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)" - Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z") -end -_jsduration(s) = occursin(_JS_DURATION, s) - -_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s) - -function _jsregexformat(s) - # syntax of PCRE (or Python) that ECMAScript does not have - occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false - try - _jsregex(s) - return true - catch - # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only - # for lookbehinds, which ECMAScript allows with variable width - return occursin("(?<", s) - end -end - -const _FORMATS = Dict{String, Function}( - "date-time" => _jsdatetime, - "date" => _jsdate, - "time" => _jstime, - "duration" => _jsduration, - "email" => _jsemail, - "idn-email" => s -> _jsemail(s; idn = true), - "hostname" => _jshostname, - "idn-hostname" => _jsidnhostname, - "ipv4" => _jsipv4, - "ipv6" => _jsipv6, - "uri" => _jsuri, - "uri-reference" => s -> _jsuri(s; absolute = false), - "iri" => s -> _jsuri(s; iri = true), - "iri-reference" => s -> _jsuri(s; absolute = false, iri = true), - "uri-template" => _jsuritemplate, - "json-pointer" => _jsjsonpointer, - "relative-json-pointer" => _jsreljsonpointer, - "uuid" => _jsuuid, - "regex" => _jsregexformat, -) - -_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) _jsisnumber(x) = x isa Real && !(x isa Bool) -function _jstypeok(t::AbstractString, x) - t == "null" && return x === nothing - t == "boolean" && return x isa Bool - t == "integer" && return _jsisinteger(x) - t == "number" && return _jsisnumber(x) - t == "string" && return x isa AbstractString - t == "array" && return x isa AbstractVector - t == "object" && return x isa AbstractDict - return true -end - # equality of JSON values: `1 == 1.0`, but `true != 1` _jseq(a, b) = a isa Bool || b isa Bool ? (a isa Bool && b isa Bool && a == b) : _jsisnumber(a) && _jsisnumber(b) ? a == b : isequal(a, b) @@ -726,232 +303,6 @@ _jseq(a::AbstractVector, b::AbstractVector) = length(a) == length(b) && all(_jse _jseq(a::AbstractDict, b::AbstractDict) = length(a) == length(b) && all(haskey(b, k) && _jseq(v, b[k]) for (k, v) in a) -function _jsallunique(x) - v = Any[_jsto(el) for el in x] - return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) -end - -""" - _jsvalid(schema, x) -> Union{Nothing, String} - -Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a -message describing the first problem found. -""" -_jsvalid(s, x) = first(_jsvalidann(s, x)) - -# Annotations collected while validating: the properties and array items that were -# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`. -_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items) -_jsbad(msg) = (msg, Set{String}(), Set{Int}()) - -""" - _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items) - -Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the -properties and the (1-based) indices of the items that the schema evaluated, as defined by -JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`. -""" -function _jsvalidann(s, x) - s === true && return _jsok() - s === false && return _jsbad("no value is allowed here") - s isa AbstractDict || return _jsok() - # A value of a generated type (from a field of a generated struct) is valid against - # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through - # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else. - if x isa AbstractSchemaObject - if haskey(s, "\$type") && length(s) == 1 - x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x)) - x = _jsto(x) - elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s)) - x = _jsto(x) - end - end - props = Set{String}() - items = Set{Int}() - addann!(ann) = (union!(props, ann[2]); union!(items, ann[3])) - - if haskey(s, "\$type") - # a generated type: the value must be convertible to it, which checks all of it - T = getfield(@__MODULE__, Symbol(s["\$type"])) - msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing - msg === nothing || return _jsbad(msg) - try - _jsfrom(T, x) - catch err - err isa SchemaValidationError || rethrow() - return _jsbad(err.msg) - end - x isa AbstractDict && union!(props, String.(keys(x))) - x isa AbstractVector && union!(items, eachindex(x)) - end - - if haskey(s, "type") - ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],) - any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))") - end - haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])") - haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))") - - if _jsisnumber(x) - haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])") - haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])") - haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) && - x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])") - haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) && - x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])") - if haskey(s, "multipleOf") - q = x / s["multipleOf"] - isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])") - end - elseif x isa AbstractString - haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])") - haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])") - haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) && - return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])") - if haskey(s, "format") && _CHECK_FORMATS[] - check = get(_FORMATS, s["format"], nothing) - check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])") - end - elseif x isa AbstractVector - haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items") - haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items") - if get(s, "uniqueItems", false) === true - for i in eachindex(x), j in firstindex(x):i-1 - _jseq(x[i], x[j]) && return _jsbad("items are not unique") - end - end - prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[]) - for (i, sub) in enumerate(prefix) - i <= length(x) || break - err = _jsvalid(sub, x[i]) - err === nothing || return _jsbad("item $i: $err") - push!(items, i) - end - rest = haskey(s, "prefixItems") ? get(s, "items", nothing) : - get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing) - if rest !== nothing - for i in (length(prefix) + 1):length(x) - err = _jsvalid(rest, x[i]) - err === nothing || return _jsbad("item $i: $err") - push!(items, i) - end - end - if haskey(s, "contains") - matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing] - n = length(matching) - lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int)) - lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi") - union!(items, matching) - end - elseif x isa AbstractDict - haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties") - haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties") - for k in get(s, "required", ()) - haskey(x, k) || return _jsbad("missing required property `$k`") - end - defined = get(s, "properties", nothing) - patterns = get(s, "patternProperties", nothing) - extra = get(s, "additionalProperties", nothing) - names = get(s, "propertyNames", nothing) - (defined === nothing && patterns === nothing && extra === nothing && names === nothing) || - for (k, v) in x - k = String(k) - matched = false - if defined !== nothing && haskey(defined, k) - matched = true - err = _jsvalid(defined[k], v) - err === nothing || return _jsbad("property `$k`: $err") - end - for (p, sub) in something(patterns, ()) - occursin(_jsregex(p), k) || continue - matched = true - err = _jsvalid(sub, v) - err === nothing || return _jsbad("property `$k`: $err") - end - if !matched && extra !== nothing - err = _jsvalid(extra, v) - err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err") - matched = true - end - matched && push!(props, k) - if names !== nothing - err = _jsvalid(names, k) - err === nothing || return _jsbad("property name `$k`: $err") - end - end - (haskey(s, "dependentRequired") || haskey(s, "dependencies")) && - for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict()))) - haskey(x, k) || continue - for d in deps - haskey(x, d) || return _jsbad("property `$k` requires property `$d`") - end - end - (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) && - for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict()))) - haskey(x, k) || continue - ann = _jsvalidann(sub, x) - ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])") - addann!(ann) - end - end - - for sub in get(s, "allOf", ()) - ann = _jsvalidann(sub, x) - ann[1] === nothing || return ann - addann!(ann) - end - if haskey(s, "anyOf") - anns = [_jsvalidann(sub, x) for sub in s["anyOf"]] - valid = filter(a -> a[1] === nothing, anns) - isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")") - foreach(addann!, valid) - end - if haskey(s, "oneOf") - valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]]) - n = length(valid) - n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" : - "matches $n options of `oneOf`, but must match exactly one") - addann!(only(valid)) - end - haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`") - if haskey(s, "if") - cond = _jsvalidann(s["if"], x) - if cond[1] === nothing - addann!(cond) - if haskey(s, "then") - ann = _jsvalidann(s["then"], x) - ann[1] === nothing || return _jsbad("`then`: " * ann[1]) - addann!(ann) - end - elseif haskey(s, "else") - ann = _jsvalidann(s["else"], x) - ann[1] === nothing || return _jsbad("`else`: " * ann[1]) - addann!(ann) - end - end - - # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this - # schema, or of its valid subschemas, evaluated - if x isa AbstractVector && haskey(s, "unevaluatedItems") - for i in eachindex(x) - i in items && continue - err = _jsvalid(s["unevaluatedItems"], x[i]) - err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err") - push!(items, i) - end - end - if x isa AbstractDict && haskey(s, "unevaluatedProperties") - for (k, v) in x - String(k) in props && continue - err = _jsvalid(s["unevaluatedProperties"], v) - err === nothing || return _jsbad(s["unevaluatedProperties"] === false ? - "property `$k` is not allowed" : "property `$k`: $err") - push!(props, String(k)) - end - end - return (nothing, props, items) -end - # --- Conversion from Julia values into JSON-compatible values --- """ @@ -975,20 +326,6 @@ _jsto(x::AbstractVector) = Any[_jsto(el) for el in x] _jsto(x::Tuple) = Any[_jsto(el) for el in x] _jsto(x::AbstractDict) = JSON.Object{String, Any}(String(k) => _jsto(v) for (k, v) in x) -# the JSON names of the properties of a value of a generated type -function _jskeys(x::T) where {T <: AbstractSchemaObject} - spec = _specs(T) - ks = Set{String}() - for f in spec.fields - v = getfield(x, f.name) - (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key) - end - if spec.extra !== nothing - union!(ks, keys(getfield(x, spec.extra))) - end - return ks -end - function _jsto(x::T) where {T <: AbstractSchemaObject} obj = JSON.Object{String, Any}() for f in _specs(T).fields @@ -1063,7 +400,7 @@ validating it against the constraints of the schema. function fromdict(::Type{T}, x) where {T} value = _jsfrom(T, x) # the root of the schema may have constraints that its type does not enforce - if _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing + if _INLINE_CHECKS && _CHECKS[] && T === RootType && _ROOT_CONSTRAINTS[] !== nothing _jsvalidate(value, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) end return value @@ -1141,23 +478,34 @@ Read the JSON file `filename` into a value of type `T`. readjson(::Type{T}, filename::AbstractString) where {T} = fromjson(T, read(filename, String)) """ - tojson(x; pretty=false, validate=!checks()) + tojson(x; pretty=false, validate) -Convert `x` into a JSON string. With `validate = true` (the default when the checks are -off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). +Convert `x` into a JSON string. With `validate = true`, `x` is first checked against the +schema with `validate`. That is the default when the values are not checked when they are +created: when the checks are off (see `checks!`), or when the module was generated with +`validation = :separate` (and its validation file is present). """ -function tojson(x; pretty::Bool = false, validate::Bool = !_CHECKS[]) - validate && _jsvalidateall(x) +function tojson(x; pretty::Bool = false, validate::Bool = _jsvalidatedefault()) + validate && _jsvalidatebeforewrite(x) return JSON.json(todict(x); pretty) end +_jsvalidatedefault() = _INLINE_CHECKS ? !_CHECKS[] : _VALIDATOR[] !== nothing + +function _jsvalidatebeforewrite(x) + v = _VALIDATOR[] + v === nothing && throw(ArgumentError("this module has no validation code: it was generated " * + "with `validation = :none`, or its validation file is missing; use `validate = false`")) + return v(x) +end + """ - writejson(filename, x; pretty=true, validate=!checks()) + writejson(filename, x; pretty=true, validate) -Write `x` as JSON to the file `filename`. With `validate = true` (the default when the -checks are off, see [`checks!`](@ref)), `x` is first checked with [`validate`](@ref). +Write `x` as JSON to the file `filename`. With `validate = true`, `x` is first checked +against the schema, as by [`tojson`](@ref), whose default it shares. """ -function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = !_CHECKS[]) +function writejson(filename::AbstractString, x; pretty::Bool = true, validate::Bool = _jsvalidatedefault()) json = tojson(x; pretty, validate) open(filename, "w") do io write(io, json) @@ -1166,118 +514,6 @@ function writejson(filename::AbstractString, x; pretty::Bool = true, validate::B return filename end -# --- Validation of whole values --- - -""" - violations(x) -> Vector{String} - -Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every -value nested in it, against all the constraints of the schema, whether or not the checks -were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per -invalid value (the first problem of each), with its location, e.g. -`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON -names of the properties and 1-based indices of the items: `recipes[1].batch_size`. -""" -function violations(x) - out = String[] - with_checks(true) do - _jscollect!(out, x, Any[]) - if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing - try - _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) - catch err - err isa SchemaValidationError || rethrow() - push!(out, err.msg) - end - end - end - return out -end - -""" - validate(x) - -Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing -the problems found, if any. Returns `x`. -""" -validate(x) = _jsvalidateall(x) - -function _jsvalidateall(x) - v = violations(x) - isempty(v) && return x - n = length(v) - _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n " * join(v, "\n ")) -end - -""" - isvalid(x::AbstractSchemaObject) -> Bool - -Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref). -""" -Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x)) - -# The location of a value is kept as a stack of property names and indices, and only -# written out (e.g. `recipes[1].batch_size`) when a problem is found. -function _jsat(path::Vector{Any}, msg) - isempty(path) && return msg - io = IOBuffer() - for (i, p) in enumerate(path) - p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p) - end - return String(take!(io)) * ": " * msg -end - -function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} - spec = _specs(T) - values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) - extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) - try - _jscheck(T, values, extra) - catch err - err isa SchemaValidationError || rethrow() - push!(out, _jsat(path, err.msg)) - end - _jscollectfields!(out, spec.fields, values, path) - extra === nothing || _jscollect!(out, extra, path) - return out -end - -# (unrolled over the tuples of field metadata and values, as `_jscheckfields`) -@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out -@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path) - v = first(values) - if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} - push!(path, first(fields).key) - _jscollect!(out, v, path) - pop!(path) - end - return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path) -end - -function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum} - _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value))) - return out -end -function _jscollect!(out, x::Union{AbstractVector, Tuple}, path) - for (i, v) in enumerate(x) - v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue - push!(path, i) - _jscollect!(out, v, path) - pop!(path) - end - return out -end -function _jscollect!(out, x::AbstractDict, path) - for (k, v) in x - v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue - push!(path, String(k)) - _jscollect!(out, v, path) - pop!(path) - end - return out -end -_jscollect!(out, x, path) = out - # --------------------------------------------------------------------------------------- # End of runtime support. Generated types follow. # --------------------------------------------------------------------------------------- diff --git a/src/runtime_validation.jl b/src/runtime_validation.jl new file mode 100644 index 0000000..9b323a9 --- /dev/null +++ b/src/runtime_validation.jl @@ -0,0 +1,812 @@ +# --------------------------------------------------------------------------------------- +# Runtime support for validating values of the generated types against their schema. +# +# This code is copied verbatim into the modules generated by JSONSchema2Types, after the +# runtime support for reading and writing (`runtime.jl`). With `validation = :inline` (the +# default), the constructors of the generated types call these checks; with +# `validation = :separate`, it is in a separate file, which provides `validate`. +# --------------------------------------------------------------------------------------- + +# --- Turning the checks off (with `validation = :inline`) --- + +""" + checks!(flag::Bool) + +Turn on or off the checks of the constraints of the schema when values of the generated +types are created (by their constructors, [`setfields`](@ref), [`fromjson`](@ref)...). +They are on by default (unless the module was generated with `checks = false`). + +With the checks off, values are only converted to the types of their fields, which still +enforce the structure of the schema (the types of the properties, required properties, +the properties allowed, enumeration types), but not its constraints (`minimum`, `pattern`, +the values of enumerations, `minItems`, `oneOf`...), for speed. Check the values later +with [`validate`](@ref), which [`tojson`](@ref) and [`writejson`](@ref) call when the +checks are off. A JSON value read into a union of generated types (from `oneOf` or +`anyOf`) is still checked, to choose its type. + +The setting is global (shared by all tasks); see [`with_checks`](@ref) to change it +temporarily. Returns the previous setting. +""" +checks!(flag::Bool) = (old = _CHECKS[]; _CHECKS[] = flag; old) + +""" + checks() -> Bool + +Whether the checks of the constraints of the schema are on; see [`checks!`](@ref). +""" +checks() = _CHECKS[] + +""" + with_checks(f, flag::Bool) + +Call `f()` with the checks of the constraints of the schema turned on or off (see +[`checks!`](@ref)), and restore the previous setting afterwards: +`with_checks(false) do ... end`. +""" +function with_checks(f, flag::Bool) + old = checks!(flag) + try + return f() + finally + _CHECKS[] = old + end +end + +# The metadata of the structs used by the checks, with their constraints: the same as +# `_specs` when the constructors check (`validation = :inline`); otherwise the validation +# file defines a method for each struct. +_vspecs(::Type{T}) where {T <: AbstractSchemaObject} = _specs(T) + +# Where a value is in a document, for the messages of the errors: built only when a check +# fails, so that valid values cost no string allocations. +struct _JSField{T} + key::String +end +Base.print(io::IO, w::_JSField{T}) where {T} = print(io, "`", w.key, "` in `", _jsname(T), "`") +struct _JSItem{W} + parent::W + index::Int +end +Base.print(io::IO, w::_JSItem) = print(io, w.parent, "[", w.index, "]") + +# --- Validation of constraints --- + +_jslength(x::AbstractString) = length(x) + +# values of typed formats (dates, UUIDs) are validated through their string form +_jsscalar(x) = x + +# `nothing` is an absent optional field, unless `null` is a value (e.g. a JSON document `null`) +function _jsvalidate(x, c, where_; null_is_value::Bool = false) + c === nothing && return nothing + x === nothing && !null_is_value && return nothing + x = _jsscalar(x) + if haskey(c, :schema) + err = _jsvalid(c.schema, x isa AbstractSchemaObject ? x : _jsto(x)) + err === nothing || _jsfail("$where_ is invalid: $err") + end + if x isa Real && !(x isa Bool) + haskey(c, :minimum) && x < c.minimum && _jsfail("$where_ must be ≥ $(c.minimum), got $x") + haskey(c, :maximum) && x > c.maximum && _jsfail("$where_ must be ≤ $(c.maximum), got $x") + haskey(c, :exclusiveMinimum) && x <= c.exclusiveMinimum && _jsfail("$where_ must be > $(c.exclusiveMinimum), got $x") + haskey(c, :exclusiveMaximum) && x >= c.exclusiveMaximum && _jsfail("$where_ must be < $(c.exclusiveMaximum), got $x") + if haskey(c, :multipleOf) + q = x / c.multipleOf + isapprox(q, round(q); atol = 1e-9) || _jsfail("$where_ must be a multiple of $(c.multipleOf), got $x") + end + elseif x isa AbstractString + haskey(c, :minLength) && _jslength(x) < c.minLength && _jsfail("$where_ must have at least $(c.minLength) characters, got $(repr(x))") + haskey(c, :maxLength) && _jslength(x) > c.maxLength && _jsfail("$where_ must have at most $(c.maxLength) characters, got $(repr(x))") + haskey(c, :pattern) && !occursin(c.pattern, x) && _jsfail("$where_ must match the pattern $(c.pattern.pattern), got $(repr(x))") + elseif x isa AbstractVector + haskey(c, :minItems) && length(x) < c.minItems && _jsfail("$where_ must have at least $(c.minItems) items, got $(length(x))") + haskey(c, :maxItems) && length(x) > c.maxItems && _jsfail("$where_ must have at most $(c.maxItems) items, got $(length(x))") + haskey(c, :uniqueItems) && c.uniqueItems && !_jsallunique(x) && _jsfail("$where_ must have unique items") + if haskey(c, :items) + for (i, el) in enumerate(x) + _jsvalidate(el, c.items, _JSItem(where_, i)) + end + end + elseif x isa AbstractDict + haskey(c, :minProperties) && length(x) < c.minProperties && _jsfail("$where_ must have at least $(c.minProperties) properties") + haskey(c, :maxProperties) && length(x) > c.maxProperties && _jsfail("$where_ must have at most $(c.maxProperties) properties") + end + return nothing +end + +""" + _jscheck(T, values, extra) + +Check the constraints of the generated struct `T` (recorded in [`_SPECS`](@ref)) on the +converted field `values` and the additional properties `extra`. Called by the inner +constructor of `T`, after [`_jsfrom`](@ref) converted each argument: it checks that +required fields are set, the constraints of each field (`minimum`, `pattern`, +`minItems`...), the subschemas checked at runtime (`not`, `oneOf`, `format`...) and the +constraints on the object as a whole (`minProperties`, `if`/`then`/`else`...). +""" +function _jscheck(::Type{T}, values::Tuple, extra) where {T <: AbstractSchemaObject} + _CHECKS[] || return nothing + spec = _vspecs(T) + nprops = (extra === nothing ? 0 : length(extra)) + _jscheckfields(T, spec.fields, values) + spec.minProperties !== nothing && nprops < spec.minProperties && + _jsfail("`$(_jsname(T))` must have at least $(spec.minProperties) properties set, got $nprops") + spec.maxProperties !== nothing && nprops > spec.maxProperties && + _jsfail("`$(_jsname(T))` must have at most $(spec.maxProperties) properties set, got $nprops") + if spec.schema !== nothing + # keywords that apply to the object as a whole (`not`, `if`, `patternProperties`...) + obj = JSON.Object{String, Any}() + for (f, v) in zip(spec.fields, values) + v === nothing && !(f.required && f.nullable) && continue + obj[f.key] = _jsto(v) + end + extra === nothing || foreach(((k, v),) -> (obj[k] = _jsto(v)), extra) + err = _jsvalid(spec.schema, obj) + err === nothing || _jsfail("`$(_jsname(T))` is invalid: $err") + end + return nothing +end + +# The checks of the fields, unrolled over the tuples of field metadata and values (the +# metadata is a constant, so this is type-stable); returns the number of properties set. +@inline _jscheckfields(::Type, ::Tuple{}, ::Tuple{}) = 0 +@inline function _jscheckfields(::Type{T}, fields::Tuple, values::Tuple) where {T} + f, v = first(fields), first(values) + if v === nothing && f.required && !f.nullable + _jsfail("required property `$(f.key)` of `$(_jsname(T))` cannot be `nothing`") + end + f.constraints === nothing || _jsvalidate(v, f.constraints, _JSField{T}(f.key)) + set = v !== nothing || (f.required && f.nullable) + return Int(set) + _jscheckfields(T, Base.tail(fields), Base.tail(values)) +end + +function _jscheckenum(::Type{T}, value) where {T <: AbstractSchemaEnum} + _CHECKS[] || return value + _jsenumok(T, value) || _jsfail(_jsenummsg(T, value)) + return value +end + +# --- Validation of JSON values against (sub)schemas --- +# +# The generated types enforce most of a schema by themselves. The remaining keywords (`not`, +# `if`/`then`/`else`, exclusivity of `oneOf`, `patternProperties`, `format`, ...) are +# checked by validating the JSON form of a value against the corresponding subschemas, +# which the generator embeds (with their `$ref`s resolved) in the metadata of the types. + +""" + check_formats!(flag::Bool) + +Enable or disable the validation of the `format` keyword. Enabled by default. The formats of +JSON Schema 2020-12 are checked (`date-time`, `date`, `time`, `duration`, `email`, +`idn-email`, `hostname`, `idn-hostname`, `ipv4`, `ipv6`, `uri`, `uri-reference`, `iri`, +`iri-reference`, `uri-template`, `json-pointer`, `relative-json-pointer`, `uuid`, `regex`); +unknown formats are not. +""" +check_formats!(flag::Bool) = (_CHECK_FORMATS[] = flag) +const _CHECK_FORMATS = Ref(true) + +const _REGEX_CACHE = Dict{String, Regex}() + +# JSON Schema patterns are ECMAScript regular expressions. They are compiled with PCRE without +# Unicode classes (so `\d` and `\w` are ASCII, as in ECMAScript) and with `$` matching only at +# the end, after translating `\s` and long Unicode property names, which PCRE lacks. +const _JS_REGEX_OPTIONS = Base.PCRE.UTF | Base.PCRE.MATCH_INVALID_UTF | Base.PCRE.ALT_BSUX | + Base.PCRE.DOLLAR_ENDONLY +_jsregex(p::AbstractString) = + get!(() -> Regex(_jsecmaregex(p), _JS_REGEX_OPTIONS, Base.DEFAULT_MATCH_OPTS), _REGEX_CACHE, p) + +const _JS_SPACES = "\\t\\n\\u000b\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff" +const _JS_PROPERTIES = Dict( + "Letter" => "L", "Cased_Letter" => "LC", "Uppercase_Letter" => "Lu", "Lowercase_Letter" => "Ll", + "Titlecase_Letter" => "Lt", "Modifier_Letter" => "Lm", "Other_Letter" => "Lo", "Mark" => "M", + "Nonspacing_Mark" => "Mn", "Spacing_Mark" => "Mc", "Enclosing_Mark" => "Me", "Number" => "N", + "Decimal_Number" => "Nd", "digit" => "Nd", "Letter_Number" => "Nl", "Other_Number" => "No", + "Punctuation" => "P", "punct" => "P", "Connector_Punctuation" => "Pc", "Dash_Punctuation" => "Pd", + "Open_Punctuation" => "Ps", "Close_Punctuation" => "Pe", "Initial_Punctuation" => "Pi", + "Final_Punctuation" => "Pf", "Other_Punctuation" => "Po", "Symbol" => "S", "Math_Symbol" => "Sm", + "Currency_Symbol" => "Sc", "Modifier_Symbol" => "Sk", "Other_Symbol" => "So", "Separator" => "Z", + "Space_Separator" => "Zs", "Line_Separator" => "Zl", "Paragraph_Separator" => "Zp", "Other" => "C", + "Control" => "Cc", "cntrl" => "Cc", "Format" => "Cf", "Surrogate" => "Cs", "Private_Use" => "Co", + "Unassigned" => "Cn", +) + +function _jsecmaregex(p::AbstractString) + out = IOBuffer() + inclass = false + i = firstindex(p) + while i <= lastindex(p) + c = p[i] + if c == '\\' && i < lastindex(p) + n = p[nextind(p, i)] + j = nextind(p, nextind(p, i)) + if n == 's' + print(out, inclass ? _JS_SPACES : "[" * _JS_SPACES * "]") + elseif n == 'S' && !inclass + print(out, "[^", _JS_SPACES, "]") + elseif (n == 'p' || n == 'P') && j <= lastindex(p) && p[j] == '{' + k = findnext('}', p, j) + k === nothing && (print(out, c, n); i = j; continue) + name = replace(p[nextind(p, j):prevind(p, k)], r"^(General_Category|gc)=" => "") + print(out, '\\', n, '{', get(_JS_PROPERTIES, name, name), '}') + j = nextind(p, k) + else + print(out, c, n) + end + i = j + continue + end + # `[]` matches nothing and `[^]` anything, in ECMAScript + if !inclass && startswith(SubString(p, i), "[^]") + print(out, "[\\s\\S]"); i = nextind(p, nextind(p, nextind(p, i))); continue + elseif !inclass && startswith(SubString(p, i), "[]") + print(out, "(?!)"); i = nextind(p, nextind(p, i)); continue + end + c == '[' && (inclass = true) + c == ']' && (inclass = false) + print(out, c) + i = nextind(p, i) + end + return String(take!(out)) +end + +# --- Checks of the `format` keyword --- +# +# Following the RFCs referenced by JSON Schema; only ASCII digits are digits, and `\z` (not +# `$`, which allows a trailing newline) anchors the patterns. + +_jsleap(y) = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) + +function _jsdate(s) + m = match(r"^([0-9]{4})-([0-9]{2})-([0-9]{2})\z", s) + m === nothing && return false + y, mo, d = parse.(Int, m.captures) + days = (31, _jsleap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) + return 1 <= mo <= 12 && 1 <= d <= days[mo] +end + +function _jstime(s) + m = match(r"^([0-9]{2}):([0-9]{2}):([0-9]{2})(\.[0-9]+)?([Zz]|([+-])([0-9]{2}):([0-9]{2}))\z", s) + m === nothing && return false + h, mi, se = parse(Int, m[1]), parse(Int, m[2]), parse(Int, m[3]) + oh, om = m[6] === nothing ? (0, 0) : (parse(Int, m[7]), parse(Int, m[8])) + (h <= 23 && mi <= 59 && se <= 60 && oh <= 23 && om <= 59) || return false + if se == 60 + # a leap second is only at 23:59:60 UTC + utc = mod(h * 60 + mi - (m[6] == "-" ? -1 : 1) * (oh * 60 + om), 24 * 60) + utc == 23 * 60 + 59 || return false + end + return true +end + +function _jsdatetime(s) + m = match(r"^([^Tt]*)[Tt](.*)\z", s) + return m !== nothing && _jsdate(m[1]) && _jstime(m[2]) +end + +function _jsipv4(s) + m = match(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z", s) + m === nothing && return false + return all(c -> (length(c) == 1 || c[1] != '0') && parse(Int, c) <= 255, m.captures) +end + +function _jsipv6(s) + (isascii(s) && !isempty(s) && !occursin(r"[^0-9A-Fa-f:.]", s)) || return false + parts = split(s, "::") + length(parts) > 2 && return false + groups(p) = isempty(p) ? String[] : split(p, ':') + gs = vcat([groups(p) for p in parts]...) + n = 0 + for (i, g) in enumerate(gs) + if occursin('.', g) + # an IPv4 address can only be the last group + (i == length(gs) && last(parts) != "" && _jsipv4(g)) || return false + n += 2 + else + occursin(r"^[0-9A-Fa-f]{1,4}\z", g) || return false + n += 1 + end + end + return length(parts) == 2 ? n <= 7 : n == 8 +end + +function _jshostname(s) + isascii(s) || return false + s = endswith(s, ".") && length(s) > 1 ? chop(s) : s + (1 <= length(s) <= 253) || return false + for label in split(s, '.') + occursin(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\z", label) || return false + # "--" in the 3rd and 4th positions is reserved (RFC 5891), except for "xn--" labels + length(label) >= 4 && label[3:4] == "--" && lowercase(label[1:2]) != "xn" && return false + end + return true +end + +# Internationalized hostnames: checked as hostnames, allowing non-ASCII letters; the +# IDNA2008 rules are not checked. +const _JS_IDN_DOTS = Regex("[\u3002\uFF0E\uFF61]") +const _JS_IDN_LABEL = Regex("^[\\p{L}\\p{N}\\p{M}\\-\u00B7\u0375\u05F3\u05F4\u30FB\u200C\u200D]+\\z") + +function _jsidnhostname(s) + s = replace(s, _JS_IDN_DOTS => ".") + (1 <= length(s) <= 253) || return false + occursin(Regex("[\\s\u302E]"), s) && return false + for label in split(endswith(s, ".") && length(s) > 1 ? chop(s) : s, '.') + (1 <= length(label) <= 63) || return false + (startswith(label, "-") || endswith(label, "-")) && return false + occursin(_JS_IDN_LABEL, label) || return false + occursin(r"^\p{M}", label) && return false + end + return true +end + +const _JS_ATEXT = raw"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]" + +function _jsemail(s; idn = false) + i = findlast('@', s) + i === nothing && return false + local_part, domain = s[1:prevind(s, i)], s[nextind(s, i):end] + atext = idn ? raw"(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]|[^\x00-\x7F])" : _JS_ATEXT + dotatom = Regex("^" * atext * "+(\\." * atext * "+)*\\z") + quoted = idn ? r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|[^\x00-\x7F]|\\[\x20-\x7E])*\"\z" : + r"^\"([\x20\x21\x23-\x5B\x5D-\x7E]|\\[\x20-\x7E])*\"\z" + (occursin(dotatom, local_part) || occursin(quoted, local_part)) || return false + if startswith(domain, "[") && endswith(domain, "]") + lit = domain[2:end-1] + return startswith(lowercase(lit), "ipv6:") ? _jsipv6(lit[6:end]) : _jsipv4(lit) + end + endswith(domain, ".") && return false + return idn ? _jsidnhostname(domain) : _jshostname(domain) +end + +# URIs and IRIs (RFC 3986 and 3987): the characters, percent-encodings, scheme and authority +const _JS_URI_CHARS = raw"A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=" +function _jsuri(s; absolute = true, iri = false) + chars = iri ? "[" * _JS_URI_CHARS * "\u00A0-\U10FFFF]" : "[" * _JS_URI_CHARS * "]" + occursin(Regex("^(" * chars * "|%[0-9A-Fa-f]{2})*\\z"), s) || return false + m = match(r"^(?:([A-Za-z][A-Za-z0-9+.-]*):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?\z", s) + m === nothing && return false + absolute && m[1] === nothing && return false + # without a scheme, a first path segment with ':' would be read as a scheme + m[1] === nothing && m[2] === nothing && occursin(r"^[^/]*:", m[3]) && return false + for part in (m[3], m[4], m[5]) + part === nothing || !occursin(r"[\[\]]", part) || return false + end + count('#', s) <= 1 || return false + if m[2] !== nothing + auth = m[2] + hm = match(r"^(?:[^@\[\]]*@)?(\[[^\]]*\]|[^:\[\]@]*)(?::([0-9]*))?\z", auth) + hm === nothing && return false + if startswith(hm[1], "[") + h = hm[1][2:end-1] + (occursin(r"^[vV][0-9A-Fa-f]+\.", h) || _jsipv6(h)) || return false + end + end + return true +end + +_jsjsonpointer(s) = occursin(r"^(/([^~/]|~[01])*)*\z", s) +_jsreljsonpointer(s) = occursin(r"^(0|[1-9][0-9]*)(#|(/([^~/]|~[01])*)*)\z", s) + +# RFC 6570: literals, and expressions `{[operator]varspec,...}` +const _JS_URI_TEMPLATE = Regex("^(?:[^\\x00-\\x20\"'%<>\\\\^`{|}\\x7F]|%[0-9A-Fa-f]{2}|" * + "\\{[+#./;?&=,!@|]?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})(?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*" * + "(?::[1-9][0-9]{0,3}|\\*)?)*\\})*\\z") +_jsuritemplate(s) = occursin(_JS_URI_TEMPLATE, s) + +# RFC 3339, appendix A: "P" (date [time] / time / week), where e.g. years and days need months +const _JS_DURATION = let D = "[0-9]+", + time = "T(?:$(D)H(?:$(D)M(?:$(D)S)?)?|$(D)M(?:$(D)S)?|$(D)S)", + date = "(?:$(D)Y(?:$(D)M(?:$(D)D)?)?|$(D)M(?:$(D)D)?|$(D)D)" + Regex("^P(?:$(date)(?:$(time))?|$(time)|$(D)W)\\z") +end +_jsduration(s) = occursin(_JS_DURATION, s) + +_jsuuid(s) = occursin(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z", s) + +function _jsregexformat(s) + # syntax of PCRE (or Python) that ECMAScript does not have + occursin(r"\(\?(P[<=>]|#|[a-zA-Z]+\))|\\a", s) && return false + try + _jsregex(s) + return true + catch + # some ECMAScript forms are not supported by PCRE: accept what PCRE rejects only + # for lookbehinds, which ECMAScript allows with variable width + return occursin("(?<", s) + end +end + +const _FORMATS = Dict{String, Function}( + "date-time" => _jsdatetime, + "date" => _jsdate, + "time" => _jstime, + "duration" => _jsduration, + "email" => _jsemail, + "idn-email" => s -> _jsemail(s; idn = true), + "hostname" => _jshostname, + "idn-hostname" => _jsidnhostname, + "ipv4" => _jsipv4, + "ipv6" => _jsipv6, + "uri" => _jsuri, + "uri-reference" => s -> _jsuri(s; absolute = false), + "iri" => s -> _jsuri(s; iri = true), + "iri-reference" => s -> _jsuri(s; absolute = false, iri = true), + "uri-template" => _jsuritemplate, + "json-pointer" => _jsjsonpointer, + "relative-json-pointer" => _jsreljsonpointer, + "uuid" => _jsuuid, + "regex" => _jsregexformat, +) + +_jsisinteger(x) = x isa Real && !(x isa Bool) && isinteger(x) + +function _jstypeok(t::AbstractString, x) + t == "null" && return x === nothing + t == "boolean" && return x isa Bool + t == "integer" && return _jsisinteger(x) + t == "number" && return _jsisnumber(x) + t == "string" && return x isa AbstractString + t == "array" && return x isa AbstractVector + t == "object" && return x isa AbstractDict + return true +end + +function _jsallunique(x) + v = Any[_jsto(el) for el in x] + return !any(_jseq(v[i], v[j]) for i in eachindex(v) for j in firstindex(v):i-1) +end + +""" + _jsvalid(schema, x) -> Union{Nothing, String} + +Validate the JSON value `x` against `schema`; return `nothing` if it is valid, or a +message describing the first problem found. +""" +_jsvalid(s, x) = first(_jsvalidann(s, x)) + +# Annotations collected while validating: the properties and array items that were +# evaluated by a (sub)schema, for `unevaluatedProperties` and `unevaluatedItems`. +_jsok(props = Set{String}(), items = Set{Int}()) = (nothing, props, items) +_jsbad(msg) = (msg, Set{String}(), Set{Int}()) + +""" + _jsvalidann(schema, x) -> (error, evaluated_properties, evaluated_items) + +Validate `x` against `schema` as [`_jsvalid`](@ref), and also return the names of the +properties and the (1-based) indices of the items that the schema evaluated, as defined by +JSON Schema 2020-12 for `unevaluatedProperties` and `unevaluatedItems`. +""" +function _jsvalidann(s, x) + s === true && return _jsok() + s === false && return _jsbad("no value is allowed here") + s isa AbstractDict || return _jsok() + # A value of a generated type (from a field of a generated struct) is valid against + # `{"\$type": "Name"}` when it is a value of that type. It is kept as it is through + # `oneOf`, `anyOf` and `allOf`, and converted to its JSON form for anything else. + if x isa AbstractSchemaObject + if haskey(s, "\$type") && length(s) == 1 + x isa getfield(@__MODULE__, Symbol(s["\$type"])) && return _jsok(_jskeys(x)) + x = _jsto(x) + elseif !all(in(("oneOf", "anyOf", "allOf")), keys(s)) + x = _jsto(x) + end + end + props = Set{String}() + items = Set{Int}() + addann!(ann) = (union!(props, ann[2]); union!(items, ann[3])) + + if haskey(s, "\$type") + # a generated type: the value must be convertible to it, which checks all of it + T = getfield(@__MODULE__, Symbol(s["\$type"])) + msg = x isa AbstractDict ? _jsmismatch(T, x) : nothing + msg === nothing || return _jsbad(msg) + v = try + _jsfrom(T, x) + catch err + err isa SchemaValidationError || rethrow() + return _jsbad(err.msg) + end + # (constructors that do not check only convert: check the converted value) + if !_INLINE_CHECKS + errs = with_checks(() -> _jscollect!(String[], v, Any[]), true) + isempty(errs) || return _jsbad(first(errs)) + end + x isa AbstractDict && union!(props, String.(keys(x))) + x isa AbstractVector && union!(items, eachindex(x)) + end + + if haskey(s, "type") + ts = s["type"] isa AbstractVector ? s["type"] : (s["type"],) + any(t -> _jstypeok(t, x), ts) || return _jsbad("expected $(join(ts, " or ")), got $(repr(x))") + end + haskey(s, "enum") && !any(v -> _jseq(v, x), s["enum"]) && return _jsbad("$(repr(x)) is not one of $(s["enum"])") + haskey(s, "const") && !_jseq(s["const"], x) && return _jsbad("expected $(repr(s["const"])), got $(repr(x))") + + if _jsisnumber(x) + haskey(s, "minimum") && x < s["minimum"] && return _jsbad("$x is less than $(s["minimum"])") + haskey(s, "maximum") && x > s["maximum"] && return _jsbad("$x is greater than $(s["maximum"])") + haskey(s, "exclusiveMinimum") && s["exclusiveMinimum"] isa Real && !(s["exclusiveMinimum"] isa Bool) && + x <= s["exclusiveMinimum"] && return _jsbad("$x is not greater than $(s["exclusiveMinimum"])") + haskey(s, "exclusiveMaximum") && s["exclusiveMaximum"] isa Real && !(s["exclusiveMaximum"] isa Bool) && + x >= s["exclusiveMaximum"] && return _jsbad("$x is not less than $(s["exclusiveMaximum"])") + if haskey(s, "multipleOf") + q = x / s["multipleOf"] + isapprox(q, round(q); atol = 1e-9) || return _jsbad("$x is not a multiple of $(s["multipleOf"])") + end + elseif x isa AbstractString + haskey(s, "minLength") && length(x) < s["minLength"] && return _jsbad("$(repr(x)) is shorter than $(s["minLength"])") + haskey(s, "maxLength") && length(x) > s["maxLength"] && return _jsbad("$(repr(x)) is longer than $(s["maxLength"])") + haskey(s, "pattern") && !occursin(_jsregex(s["pattern"]), x) && + return _jsbad("$(repr(x)) does not match the pattern $(s["pattern"])") + if haskey(s, "format") && _CHECK_FORMATS[] + check = get(_FORMATS, s["format"], nothing) + check === nothing || check(x) || return _jsbad("$(repr(x)) is not a valid $(s["format"])") + end + elseif x isa AbstractVector + haskey(s, "minItems") && length(x) < s["minItems"] && return _jsbad("fewer than $(s["minItems"]) items") + haskey(s, "maxItems") && length(x) > s["maxItems"] && return _jsbad("more than $(s["maxItems"]) items") + if get(s, "uniqueItems", false) === true + for i in eachindex(x), j in firstindex(x):i-1 + _jseq(x[i], x[j]) && return _jsbad("items are not unique") + end + end + prefix = get(s, "prefixItems", get(s, "items", nothing) isa AbstractVector ? s["items"] : Any[]) + for (i, sub) in enumerate(prefix) + i <= length(x) || break + err = _jsvalid(sub, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + rest = haskey(s, "prefixItems") ? get(s, "items", nothing) : + get(s, "items", nothing) isa AbstractVector ? get(s, "additionalItems", nothing) : get(s, "items", nothing) + if rest !== nothing + for i in (length(prefix) + 1):length(x) + err = _jsvalid(rest, x[i]) + err === nothing || return _jsbad("item $i: $err") + push!(items, i) + end + end + if haskey(s, "contains") + matching = [i for i in eachindex(x) if _jsvalid(s["contains"], x[i]) === nothing] + n = length(matching) + lo = get(s, "minContains", 1); hi = get(s, "maxContains", typemax(Int)) + lo <= n <= hi || return _jsbad("$n items match `contains`; expected between $lo and $hi") + union!(items, matching) + end + elseif x isa AbstractDict + haskey(s, "minProperties") && length(x) < s["minProperties"] && return _jsbad("fewer than $(s["minProperties"]) properties") + haskey(s, "maxProperties") && length(x) > s["maxProperties"] && return _jsbad("more than $(s["maxProperties"]) properties") + for k in get(s, "required", ()) + haskey(x, k) || return _jsbad("missing required property `$k`") + end + defined = get(s, "properties", nothing) + patterns = get(s, "patternProperties", nothing) + extra = get(s, "additionalProperties", nothing) + names = get(s, "propertyNames", nothing) + (defined === nothing && patterns === nothing && extra === nothing && names === nothing) || + for (k, v) in x + k = String(k) + matched = false + if defined !== nothing && haskey(defined, k) + matched = true + err = _jsvalid(defined[k], v) + err === nothing || return _jsbad("property `$k`: $err") + end + for (p, sub) in something(patterns, ()) + occursin(_jsregex(p), k) || continue + matched = true + err = _jsvalid(sub, v) + err === nothing || return _jsbad("property `$k`: $err") + end + if !matched && extra !== nothing + err = _jsvalid(extra, v) + err === nothing || return _jsbad(extra === false ? "property `$k` is not allowed" : "property `$k`: $err") + matched = true + end + matched && push!(props, k) + if names !== nothing + err = _jsvalid(names, k) + err === nothing || return _jsbad("property name `$k`: $err") + end + end + (haskey(s, "dependentRequired") || haskey(s, "dependencies")) && + for (k, deps) in merge(get(s, "dependentRequired", Dict()), filter(p -> p[2] isa AbstractVector, get(s, "dependencies", Dict()))) + haskey(x, k) || continue + for d in deps + haskey(x, d) || return _jsbad("property `$k` requires property `$d`") + end + end + (haskey(s, "dependentSchemas") || haskey(s, "dependencies")) && + for (k, sub) in merge(get(s, "dependentSchemas", Dict()), filter(p -> !(p[2] isa AbstractVector), get(s, "dependencies", Dict()))) + haskey(x, k) || continue + ann = _jsvalidann(sub, x) + ann[1] === nothing || return _jsbad("when `$k` is present: $(ann[1])") + addann!(ann) + end + end + + for sub in get(s, "allOf", ()) + ann = _jsvalidann(sub, x) + ann[1] === nothing || return ann + addann!(ann) + end + if haskey(s, "anyOf") + anns = [_jsvalidann(sub, x) for sub in s["anyOf"]] + valid = filter(a -> a[1] === nothing, anns) + isempty(valid) && return _jsbad("does not match any option of `anyOf` (" * join(first.(anns), "; ") * ")") + foreach(addann!, valid) + end + if haskey(s, "oneOf") + valid = filter(a -> a[1] === nothing, [_jsvalidann(sub, x) for sub in s["oneOf"]]) + n = length(valid) + n == 1 || return _jsbad(n == 0 ? "does not match any option of `oneOf`" : + "matches $n options of `oneOf`, but must match exactly one") + addann!(only(valid)) + end + haskey(s, "not") && _jsvalid(s["not"], x) === nothing && return _jsbad("must not match the schema in `not`") + if haskey(s, "if") + cond = _jsvalidann(s["if"], x) + if cond[1] === nothing + addann!(cond) + if haskey(s, "then") + ann = _jsvalidann(s["then"], x) + ann[1] === nothing || return _jsbad("`then`: " * ann[1]) + addann!(ann) + end + elseif haskey(s, "else") + ann = _jsvalidann(s["else"], x) + ann[1] === nothing || return _jsbad("`else`: " * ann[1]) + addann!(ann) + end + end + + # `unevaluatedItems` and `unevaluatedProperties` apply to what no other keyword of this + # schema, or of its valid subschemas, evaluated + if x isa AbstractVector && haskey(s, "unevaluatedItems") + for i in eachindex(x) + i in items && continue + err = _jsvalid(s["unevaluatedItems"], x[i]) + err === nothing || return _jsbad(s["unevaluatedItems"] === false ? "item $i is not allowed" : "item $i: $err") + push!(items, i) + end + end + if x isa AbstractDict && haskey(s, "unevaluatedProperties") + for (k, v) in x + String(k) in props && continue + err = _jsvalid(s["unevaluatedProperties"], v) + err === nothing || return _jsbad(s["unevaluatedProperties"] === false ? + "property `$k` is not allowed" : "property `$k`: $err") + push!(props, String(k)) + end + end + return (nothing, props, items) +end + +# the JSON names of the properties of a value of a generated type +function _jskeys(x::T) where {T <: AbstractSchemaObject} + spec = _specs(T) + ks = Set{String}() + for f in spec.fields + v = getfield(x, f.name) + (v !== nothing || (f.required && f.nullable)) && push!(ks, f.key) + end + if spec.extra !== nothing + union!(ks, keys(getfield(x, spec.extra))) + end + return ks +end + +# --- Validation of whole values --- + +""" + violations(x) -> Vector{String} + +Check `x` (a value of a generated type, or a vector, dict or tuple of them), and every +value nested in it, against all the constraints of the schema, whether or not the checks +were on when they were created (see [`checks!`](@ref)). Returns the problems found, one per +invalid value (the first problem of each), with its location, e.g. +`"batch_size: `value` in `VolumeType` must be ≥ 0, got -1.0"`. The location uses the JSON +names of the properties and 1-based indices of the items: `recipes[1].batch_size`. +""" +function violations(x) + out = String[] + with_checks(true) do + _jscollect!(out, x, Any[]) + if x isa RootType && _ROOT_CONSTRAINTS[] !== nothing + try + _jsvalidate(x, _ROOT_CONSTRAINTS[], "the document"; null_is_value = true) + catch err + err isa SchemaValidationError || rethrow() + push!(out, err.msg) + end + end + end + return out +end + +""" + validate(x) + +Check `x` as [`violations`](@ref) does, and throw a [`SchemaValidationError`](@ref) listing +the problems found, if any. Returns `x`. +""" +validate(x) = _jsvalidateall(x) + +function _jsvalidateall(x) + v = violations(x) + isempty(v) && return x + n = length(v) + _jsfail("$n value$(n == 1 ? " does" : "s do") not conform to the schema:\n " * join(v, "\n ")) +end + +""" + isvalid(x::AbstractSchemaObject) -> Bool + +Whether `x`, and every value nested in it, conforms to the schema; see [`violations`](@ref). +""" +Base.isvalid(x::Union{AbstractSchemaObject, AbstractSchemaEnum}) = isempty(violations(x)) + +# The location of a value is kept as a stack of property names and indices, and only +# written out (e.g. `recipes[1].batch_size`) when a problem is found. +function _jsat(path::Vector{Any}, msg) + isempty(path) && return msg + io = IOBuffer() + for (i, p) in enumerate(path) + p isa Integer ? print(io, "[", p, "]") : print(io, i == 1 ? "" : ".", p) + end + return String(take!(io)) * ": " * msg +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaObject} + spec = _vspecs(T) + values = ntuple(i -> getfield(x, spec.fields[i].name), Val(length(spec.fields))) + extra = spec.extra === nothing ? nothing : getfield(x, spec.extra) + try + _jscheck(T, values, extra) + catch err + err isa SchemaValidationError || rethrow() + push!(out, _jsat(path, err.msg)) + end + _jscollectfields!(out, spec.fields, values, path) + extra === nothing || _jscollect!(out, extra, path) + return out +end + +# (unrolled over the tuples of field metadata and values, as `_jscheckfields`) +@inline _jscollectfields!(out, ::Tuple{}, ::Tuple{}, path) = out +@inline function _jscollectfields!(out, fields::Tuple, values::Tuple, path) + v = first(values) + if v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} + push!(path, first(fields).key) + _jscollect!(out, v, path) + pop!(path) + end + return _jscollectfields!(out, Base.tail(fields), Base.tail(values), path) +end + +function _jscollect!(out, x::T, path) where {T <: AbstractSchemaEnum} + _jsenumok(T, x.value) || push!(out, _jsat(path, _jsenummsg(T, x.value))) + return out +end +function _jscollect!(out, x::Union{AbstractVector, Tuple}, path) + for (i, v) in enumerate(x) + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, i) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +function _jscollect!(out, x::AbstractDict, path) + for (k, v) in x + v isa Union{AbstractSchemaObject, AbstractSchemaEnum, AbstractVector, Tuple, AbstractDict} || continue + push!(path, String(k)) + _jscollect!(out, v, path) + pop!(path) + end + return out +end +_jscollect!(out, x, path) = out + +# the validation of values before writing them (see `tojson`) +_VALIDATOR[] = _jsvalidateall diff --git a/test/json-schema-test-suite/run.jl b/test/json-schema-test-suite/run.jl index 5777fb2..c063e5f 100644 --- a/test/json-schema-test-suite/run.jl +++ b/test/json-schema-test-suite/run.jl @@ -11,12 +11,16 @@ # Writes a report with the results by file (to `report.md`, if given) and prints a summary. # With `--min-passed=N`, exits with an error if fewer than N tests pass (used in CI, with # the number in `test/json-schema-test-suite/BASELINE`, to catch regressions). +# With `--validation=separate`, the modules are generated with `validation = :separate` +# (constructors that do not check), and each instance is read and then checked with +# `validate`. using JSONSchema2Types using JSON const DIALECT = 2020 const METASCHEMA = "https://json-schema.org/draft/2020-12/schema" +const VALIDATION = Ref(:inline) # whether a test case applies to `version` (see the README of the test suite) function compatible(compat, version = DIALECT) @@ -55,7 +59,7 @@ function run_case(file, case) tags = get(case, "tags", String[]) M = try file_jl = generate_module(schema_file, joinpath(dir, "Generated.jl"); root_name = "Root", - module_name = "Generated", download = fetch) + module_name = "Generated", download = fetch, validation = VALIDATION[]) Base.include(Module(), file_jl) catch err msg = first(sprint(showerror, err), 300) @@ -69,9 +73,10 @@ function run_case(file, case) fromdict, RootType = binding(:fromdict), binding(:RootType) ValidationError = binding(:SchemaValidationError) Base.invokelatest(binding(:check_formats!), !("format-annotation" in tags)) + validate = VALIDATION[] === :inline ? identity : binding(:validate) for t in case["tests"] result, msg = try - Base.invokelatest(fromdict, RootType, t["data"]) + Base.invokelatest(validate, Base.invokelatest(fromdict, RootType, t["data"])) t["valid"] ? (:pass, "") : (:fail, "accepted an invalid instance") catch err if err isa ValidationError @@ -122,6 +127,7 @@ end if abspath(PROGRAM_FILE) == @__FILE__ options = filter(startswith("--"), ARGS) paths = filter(!startswith("--"), ARGS) + "--validation=separate" in options && (VALIDATION[] = :separate) outcomes = run_suite(paths[1]) if length(paths) >= 2 open(io -> report(io, outcomes), paths[2], "w") diff --git a/test/runtests.jl b/test/runtests.jl index b693913..92de188 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -369,6 +369,83 @@ end @test occursin("\nchecks!(false)\n", code) end +# (called with `invokelatest`, after loading a generated module) +function check_separate(M, vfile, file, sample) + @test !M._INLINE_CHECKS && isdefined(M, :validate) && :validate in names(M) + # reading and writing every sample, unchanged + for f in readdir(joinpath(SAMPLES, "converted"); join = true) + endswith(f, ".json") || continue + doc = M.readjson(M.RootType, f) + @test approx(canon(JSON.parse(M.tojson(doc))), canon(JSON.parse(read(f, String)))) + @test isvalid(doc) + end + doc = M.readjson(M.RootType, sample) + recipe = only(doc.beerjson.recipes) + # the constructors do not check the constraints... + v = M.VolumeType(unit = "litre", value = 20) + @test v.unit.value == "litre" && !isvalid(v) + bad = M.setfields(recipe; batch_size = v) + @test M.violations(bad) == ["batch_size.unit: " * M._jsenummsg(M.VolumeUnitType, "litre")] + @test_throws M.SchemaValidationError M.validate(bad) + # ...but writing does, by default + @test_throws M.SchemaValidationError M.tojson(bad) + @test_throws M.SchemaValidationError M.writejson(joinpath(mktempdir(), "r.json"), bad) + @test JSON.parse(M.tojson(bad; validate = false))["batch_size"]["unit"] == "litre" + # the structure is still enforced, and unions are chosen by structure and enum values + @test_throws UndefKeywordError M.VolumeType(unit = "l") + @test_throws M.SchemaValidationError M.VolumeType(unit = "l", value = "x") + hop = recipe.ingredients.hop_additions[1] + @test M.setfields(hop; amount = (unit = "l", value = 1)).amount isa M.VolumeType + @test M.setfields(hop; amount = (unit = "kg", value = 1)).amount isa M.MassType + @test_throws M.SchemaValidationError M.setfields(hop; amount = (unit = "litre", value = 1)) + # a `oneOf` checked by `validate` with values of generated types built without checks + @test isvalid(M.setfields(hop; amount = M.MassType(unit = "kg", value = 1))) + # without the validation file, the module only reads and writes + rm(vfile) + N = Base.include(Module(), file) + Base.invokelatest(check_without_validation, N, sample) +end + +function check_without_validation(N, sample) + @test !isdefined(N, :validate) && !isdefined(N, :violations) + doc = N.readjson(N.RootType, sample) + @test approx(canon(JSON.parse(N.tojson(doc))), canon(JSON.parse(read(sample, String)))) + bad = N.setfields(only(doc.beerjson.recipes); batch_size = (unit = "litre", value = 20)) + @test occursin("litre", N.tojson(bad)) + @test_throws ArgumentError N.tojson(bad; validate = true) +end + +@testset "Minimal types, with the validation in a separate file" begin + beer = joinpath(EXAMPLES, "beerjson-1.0.1", "json", "beer.json") + sample = joinpath(SAMPLES, "converted", "punk-ipa-2010-current.json") + @test_throws ArgumentError generate_module(beer, joinpath(mktempdir(), "x.jl"); validation = :other) + @test_throws ArgumentError generate_module(beer, joinpath(mktempdir(), "x.jl"); validation = :none, checks = false) + for split in (true, false) + out = joinpath(mktempdir(), split ? "Beer" : "Beer.jl") + file = generate_module(beer, out; root_name = "BeerJSON", split, validation = :separate) + vfile = split ? joinpath(out, "validation.jl") : joinpath(dirname(out), "Beer_validation.jl") + @test isfile(vfile) + main = read(file, String) + @test !occursin("_jscheck", main) && occursin("const _INLINE_CHECKS = false", main) + split && @test !isfile(joinpath(out, "runtime_validation.jl")) + M = Base.include(Module(), file) + Base.invokelatest(check_separate, M, vfile, file, sample) + end + # `:none`: no validation file at all + out = joinpath(mktempdir(), "Beer") + file = generate_module(beer, out; root_name = "BeerJSON", split = true, validation = :none) + @test sort(filter(f -> occursin("valid", f), readdir(out))) == String[] + @test !occursin("validation.jl", read(file, String)) + M = Base.include(Module(), file) + @test !isdefined(M, :validate) && !isdefined(M, :check_formats!) + @test M.readjson(M.RootType, sample) isa M.RootType + # the committed example + A = Base.include(Module(), joinpath(EXAMPLES, "generated", "AcmeNestedMinimal.jl")) + p = A.Product(productId = 1, productName = "x", price = -1) + @test A.violations(p) == ["`price` in `Product` must be > 0, got -1.0"] +end + + @testset "Defaults" begin schema = joinpath(@__DIR__, "schemas", "defaults.json") # by default, optional fields are `nothing` @@ -537,7 +614,7 @@ end main = generate_module(schema, dir; split = true) @test main == joinpath(dir, "LibraryTypes.jl") # `author.json` and `book.json` use each other, so they share a file, after `common.json` - @test sort(readdir(dir)) == ["LibraryTypes.jl", "author_and_book.jl", "common.jl", "root.jl", "runtime.jl"] + @test sort(readdir(dir)) == ["LibraryTypes.jl", "author_and_book.jl", "common.jl", "root.jl", "runtime.jl", "runtime_validation.jl"] code = read(main, String) @test findfirst("include(\"common.jl\")", code) < findfirst("include(\"author_and_book.jl\")", code) < findfirst("include(\"root.jl\")", code) @@ -584,6 +661,7 @@ end @testset "Committed examples load" begin for file in readdir(joinpath(EXAMPLES, "generated"); join = true) + endswith(file, "_validation.jl") && continue # (included by its module) isdir(file) && (file = joinpath(file, basename(file) * ".jl")) @test Base.include(Module(), file) isa Module end