Ai::Schema

Beta

JSON Schema for LLM tools and structured outputs: compiles a schema into a flat program, validates JSON against it with no DOM, whole or in chunks, generates the schema from a C++ type and repairs the JSON a model wrote.

Optional module: turn it on with -DETHEREAL_AI_SCHEMA=ONInclude #include <ethereal/cpp/ai/schema/schema_inc.hpp>C layer

schema_inc.hpp

#include <ethereal/cpp/ai/schema/schema_inc.hpp>

Everything of the Ai::Schema module, in one include.

Needs the library built with ETHEREAL_AI_SCHEMA (the macro ETL_AI_SCHEMA is then defined).

schema_describe.hpp

#include <ethereal/cpp/ai/schema/schema_describe.hpp>

C++ types as JSON Schema: SchemaOf, the direct decoder into a struct (CDecoder, Decode) and the encoder (Encode).

A struct is described once, with the Meta module, and the schema attributes of this header join the Meta ones:

struct SWeatherArgs { char sCity[ 64 ]; EUnit eUnit; ETL_INT32 iDays; };

ETL_META_DESCRIBE( SWeatherArgs, ETL_META_FIELD( sCity, Meta::Description( "City name" ), Schema::MinLength( 1 ) ), ETL_META_FIELD( eUnit, Meta::Description( "Temperature unit" ) ), ETL_META_FIELD( iDays, Meta::Range( 1, 14 ) ) );

From the description, at compile time, comes a table of the type (Detail::STypeDesc). One engine in the library, with no templates, walks that table to write the schema, to decode JSON into the struct and to encode the struct into JSON. The three agree by construction: the decoder checks exactly what SchemaOf writes, with the keywords and the JSON Pointers the validator would give.

Types: bool, the integers of 8 to 64 bits, float, double, enums described with ETL_META_ENUM (the JSON name is derived like a field name: 'eMetersPerSecond' is "meters_per_second"), char[N] (up to N - 1 bytes and a terminator), std::string_view (into the input, or into the arena when the text had escapes), described structs, Containers::CFixedVector, std::array, T[N], std::span (the items in the arena) and std::optional.

A string or number attribute on a container or an optional applies to its items, or to its value: MaxLength( 8 ) on a span of string views limits each string. MinItems, MaxItems and UniqueItems apply to the container.

struct

MinLength

Ethereal::Ai::Schema#
C++
struct   MinLength : Meta::SAttribute
{
    ETL_UINT64    uValue;
    constexpr explicit MinLength( const ETL_UINT64 u ) noexcept : uValue( u ) {}
};

'minLength': the string has at least this many code points.

struct

MaxLength

Ethereal::Ai::Schema#
C++
struct   MaxLength : Meta::SAttribute
{
    ETL_UINT64    uValue;
    constexpr explicit MaxLength( const ETL_UINT64 u ) noexcept : uValue( u ) {}
};

'maxLength': the string has at most this many code points.

struct

Pattern

Ethereal::Ai::Schema#
C++
struct   Pattern : Meta::SAttribute
{
    std::string_view    sPattern;
    constexpr explicit Pattern( const std::string_view s ) noexcept : sPattern( s ) {}
};

'pattern': an ECMA-262 regular expression the string matches somewhere.

struct

Format

Ethereal::Ai::Schema#
C++
struct   Format : Meta::SAttribute
{
    EFormat        eFormat;
    constexpr explicit Format( const EFormat e ) noexcept : eFormat( e ) {}
};

'format': date-time, email, uuid and the others of EFormat.

struct

MinItems

Ethereal::Ai::Schema#
C++
struct   MinItems : Meta::SAttribute
{
    ETL_UINT64    uValue;
    constexpr explicit MinItems( const ETL_UINT64 u ) noexcept : uValue( u ) {}
};

'minItems'.

struct

MaxItems

Ethereal::Ai::Schema#
C++
struct   MaxItems : Meta::SAttribute
{
    ETL_UINT64    uValue;
    constexpr explicit MaxItems( const ETL_UINT64 u ) noexcept : uValue( u ) {}
};

'maxItems'.

struct

UniqueItems

Ethereal::Ai::Schema#
C++
struct   UniqueItems : Meta::SAttribute {};

'uniqueItems': true. Only on containers of scalars and strings.

struct

Minimum

Ethereal::Ai::Schema#
C++
template < typename T >
struct   Minimum : Meta::SAttribute
{
    T    tValue;
    constexpr explicit Minimum( const T t ) noexcept : tValue( t ) {}
};

'minimum' alone (Meta::Range gives both ends).

struct

Maximum

Ethereal::Ai::Schema#
C++
template < typename T >
struct   Maximum : Meta::SAttribute
{
    T    tValue;
    constexpr explicit Maximum( const T t ) noexcept : tValue( t ) {}
};

'maximum' alone.

struct

ExclusiveMinimum

Ethereal::Ai::Schema#
C++
template < typename T >
struct   ExclusiveMinimum : Meta::SAttribute
{
    T    tValue;
    constexpr explicit ExclusiveMinimum( const T t ) noexcept : tValue( t ) {}
};

'exclusiveMinimum'.

struct

ExclusiveMaximum

Ethereal::Ai::Schema#
C++
template < typename T >
struct   ExclusiveMaximum : Meta::SAttribute
{
    T    tValue;
    constexpr explicit ExclusiveMaximum( const T t ) noexcept : tValue( t ) {}
};

'exclusiveMaximum'.

struct

MultipleOf

Ethereal::Ai::Schema#
C++
template < typename T >
struct   MultipleOf : Meta::SAttribute
{
    T    tValue;
    constexpr explicit MultipleOf( const T t ) noexcept : tValue( t ) {}
};

'multipleOf', greater than zero.

struct

Title

Ethereal::Ai::Schema#
C++
struct   Title : Meta::SAttribute
{
    std::string_view    sText;
    constexpr explicit Title( const std::string_view s ) noexcept : sText( s ) {}
};

'title', an annotation.

function

SchemaOf

Ethereal::Ai::Schema#
template < typename T > std::string_view SchemaOf( void ) noexcept
function

SchemaOf

Ethereal::Ai::Schema#
template < typename T > std::string_view SchemaOf( const EDialect eDialect ) noexcept

The schema of the type in the shape eDialect accepts (schema_dialect.hpp).

eAnthropic and eMcp take the eGeneric text as it is. The others:

  • eAnthropicStrict: no minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, minLength, maxLength, maxItems or uniqueItems, and minItems only up to 1;
  • eOpenAIStrict: every field in 'required', the optional ones as a union with null; no minLength, maxLength, uniqueItems, default or the format uri;
  • eMcpElicitation: no exclusive bounds, multipleOf, pattern or uniqueItems, the formats email, uri, date and date-time only, and no 'additionalProperties' (a type with structs or containers inside cannot be a form: CheckDialect says so).

What a dialect leaves out goes at the end of the description, as the providers' SDKs do: "Constraints: minimum 1, at most 63 characters.". The decoder checks the whole type whatever the dialect: give it the dialect in SDecodeOptions to accept the null of an optional field of eOpenAIStrict.

The schema, or an empty view on lack of memory or an unknown dialect.
struct

SDecodeOptions

Ethereal::Ai::Schema#
C++
struct   SDecodeOptions
{
    /// @brief  Nesting of the instance (structs and containers). Deeper is
    ///             eDepthLimit. The type bounds the nesting of a valid document: the
    ///             limit guards the unknown fields that bIgnoreUnknownFields skips.
    ETL_UINT32                uMaxDepth = 64u;

    /// @brief  Size of the document.
    std::size_t                uMaxDocumentBytes = std::size_t( 64u ) << 20;

    /// @brief  A property the struct does not have is skipped, instead of the error
    ///             'additionalProperties' that the schema gives. For models that add
    ///             fields of their own.
    bool                    bIgnoreUnknownFields = false;

    /// @brief  The dialect the schema went out in. With eOpenAIStrict, a null in an
    ///             optional field that is not a std::optional means it is missing (that
    ///             dialect writes optional fields as a union with null). The checks stay
    ///             the ones of the whole type in every dialect.
    EDialect                eDialect = EDialect::eGeneric;

    /// @brief  Allocator of the decoder (its state, the compiled patterns). Null is
    ///             Memory::DefaultAllocator. The values go to the arena.
    Memory::IAllocator *    pAllocator = nullptr;
};

Options of a decode.

class

CDecoder

Ethereal::Ai::Schema#

Decodes JSON straight into a described type, checking it as it reads.

class CDecoder

No DOM: the reader's events go into the fields. The checks are the ones of SchemaOf, and an error is reported with the keyword, the JSON Pointer and the position the validator would give for the schema (the first error only: the decode stops there). sDetail carries the type names, the pattern, the format and the missing property. The bounds of numbers are not in sDetail.

A property that is missing and has Meta::Default gets the default. A missing std::optional is emptied. Any other missing optional field keeps the value it had. On error the value is partly decoded.

A std::string_view points into the input when the text has no escape, and into the arena when it has: the input and the arena must outlive the value. The items of a span go to the arena.

Movable, not copyable. For one thread. Keeps its memory from one document to the next: after the first documents, a decode allocates nothing (the arena aside, which belongs to the caller).

constructor

CDecoder

#
CDecoder() noexcept = default;

A decoder with the default options.

constructor

CDecoder

#
explicit CDecoder( const SDecodeOptions & Options ) noexcept : m_Options( Options )

A decoder with these options.

constructor

CDecoder

#
CDecoder( CDecoder && o ) noexcept;

Takes the state of o.

operator

operator=

#
CDecoder & operator=( CDecoder && o ) noexcept;

Frees this state and takes the one of o.

function

Decode

#
template < typename T > EStatus Decode( const std::string_view sJson, T & Out, SValidationReport & Report, Memory::CMemoryArena * pArena = nullptr ) noexcept

Decodes sJson into Out.

sJson
The document, UTF-8.
Out
Receives the value.
Report
Receives the result: eOk with bValid, or the error.
pArena
Where string views with escapes and the items of spans go. May be null for a type with neither (eInvalidArgument when one turns up).
Report.eStatus.
function

Options

#
const SDecodeOptions & Options( void ) const noexcept

The options in use.

function

DecodeErased

#
EStatus DecodeErased( std::string_view sJson, const Detail::STypeDesc & Desc, void * pOut, SValidationReport & Report, Memory::CMemoryArena * pArena ) noexcept;

Decode, with the type given by its table.

function

Decode

Ethereal::Ai::Schema#
template < typename T > EStatus Decode( const std::string_view sJson, T & Out, SValidationReport & Report, Memory::CMemoryArena * pArena = nullptr, const SDecodeOptions & Options = {} ) noexcept

Decodes with a decoder of its own (it allocates on each call: to decode many documents, keep a CDecoder).

function

Encode

Ethereal::Ai::Schema#
template < typename T > EStatus Encode( const T & In, const std::span< char > Out, std::size_t * const pWritten = nullptr ) noexcept

Writes the value as compact JSON in the caller's buffer, with no allocation.

The fields in the order of the description, Meta::Skip left out, an empty std::optional left out. The value is not checked against the schema: the encoder writes what it is given. A float goes out in the shortest form that reads back as the same double, and so as the same float.

In
The value.
Out
Destination. May be empty, to measure.
pWritten
Receives the size of the document, written or not. May be null.
eOk, eBufferTooSmall (with the size needed in *pWritten), eInvalidArgument (an enum value with no name, a string that is not UTF-8, NaN or infinity) or eNotLicensed.

schema_dialect.hpp

#include <ethereal/cpp/ai/schema/schema_dialect.hpp>

The dialects of the providers: which schemas Anthropic, OpenAI and MCP accept, and the checker that lists every keyword or shape a provider would refuse.

The rules come from the official pages, read on 07-11-2026 and again on 09-11-2026. A violation is an error when the page says the provider does not accept it, and a warning when the page is silent about it: a provider may take it, may drop it, or may refuse it.

SchemaOf< T >( EDialect ) writes the schema of a described type in the shape each dialect accepts (schema_describe.hpp).

enum

EDialect

Ethereal::Ai::Schema#
C++
enum class   EDialect : ETL_UINT8
{
    /// @brief  JSON Schema 2020-12 in the subset of the module, with no provider
    ///             rules. What SchemaOf< T >() writes.
    eGeneric = 0,

    /// @brief  Anthropic, the 'input_schema' of a tool without 'strict'. The page
    ///             lists no restriction beyond a JSON Schema object.
    eAnthropic,

    /// @brief  Anthropic structured outputs ('output_config.format') and strict tool
    ///             use ('strict': true): no numeric or length constraints, minItems
    ///             only 0 or 1, 'additionalProperties': false on every object, no
    ///             recursion, simple patterns, and limits on optional and union
    ///             parameters.
    eAnthropicStrict,

    /// @brief  OpenAI structured outputs with 'strict': true: the root an object
    ///             without anyOf, every property in 'required' (optional is a union
    ///             with null), 'additionalProperties': false on every object, no allOf
    ///             or not, the size limits.
    eOpenAIStrict,

    /// @brief  MCP, the 'inputSchema' of a tool (revision 2026-07-28). Any 2020-12
    ///             schema object. A root of type object is only recommended. For an
    ///             'outputSchema' use eGeneric: it has no rule beyond 2020-12.
    eMcp,

    /// @brief  MCP elicitation, the 'requestedSchema' of form mode: a flat object of
    ///             primitive properties (string, number, integer, boolean, enum).
    eMcpElicitation,

    /// @brief  Number of dialects.
    eCount
};

Where a schema goes.

function

DialectName

Ethereal::Ai::Schema#
const char * DialectName( EDialect eDialect ) noexcept;

The dialect as a name ("openai-strict"). Never null.

enum

EDialectRule

Ethereal::Ai::Schema#
C++
enum class   EDialectRule : ETL_UINT8
{
    eKeyword = 0,            /// The keyword is not accepted (eKeyword says which).
    eKeywordValue,            /// The keyword is accepted, this value is not (a format, minItems, an enum of containers).
    eAdditionalProperties,    /// An object without 'additionalProperties': false.
    eNotRequired,            /// A property outside 'required' (sDetail is its name).
    eRootNotObject,            /// The root is not a schema of type object.
    eRootAnyOf,                /// The root uses anyOf.
    eRecursive,                /// The schema refers back to itself.
    eRefInAllOf,            /// A '$ref' inside allOf.
    ePattern,                /// The pattern uses a construct the provider does not run (sDetail says which).
    eNotFlat,                /// Elicitation: a property that is not a primitive.
    eLimit,                    /// A size limit of the provider (sDetail says which).
    eIgnoredKeyword            /// The lenient parse ignored this keyword: the check could not look at it.
};

What a violation breaks.

enum

ESeverity

Ethereal::Ai::Schema#
C++
enum class   ESeverity : ETL_UINT8
{
    eError = 0,        /// The provider's page says it is not accepted.
    eWarning        /// The page does not mention it, or only recommends against it.
};

How sure the refusal is.

const

kDialectMaxViolations

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kDialectMaxViolations = 32u;

Most violations a report holds. The counts go on beyond it.

struct

SDialectViolation

Ethereal::Ai::Schema#
C++
struct   SDialectViolation
{
    EDialectRule        eRule = EDialectRule::eKeyword;
    ESeverity            eSeverity = ESeverity::eError;

    /// @brief  The keyword, or eNone when the rule is not about one.
    EKeyword            eKeyword = EKeyword::eNone;

    /// @brief  The schema node (CSchemaDocument::Node), kNoNode for a limit of the whole.
    ETL_UINT32            uSchemaNode = kNoNode;

    /// @brief  JSON Pointer of the node in the schema, zero terminated.
    char                aPointer[ kSchemaPointerBytes ] = {};
    bool                bPointerTruncated = false;

    /// @brief  What the rule refers to: the property name, the format, the construct of
    ///             the pattern, the limit. A view into the document or a static text.
    std::string_view    sDetail;

    /// @brief  Static message, in English.
    const char *        pMessage = "";
};

One thing the dialect does not accept.

struct

SDialectReport

Ethereal::Ai::Schema#
C++
struct   SDialectReport
{
    /// @brief  eOk when the check ran. eInvalidArgument for an empty schema or an
    ///             unknown dialect, eNotLicensed.
    EStatus                eStatus = EStatus::eOk;

    EDialect            eDialect = EDialect::eGeneric;

    /// @brief  No error (warnings allowed).
    bool                bCompatible = false;

    /// @brief  All found, also the ones beyond the array.
    ETL_UINT32            uErrors = 0;
    ETL_UINT32            uWarnings = 0;

    /// @brief  In aViolations, in a fixed order: the nodes in the order of the
    ///             document, and the limits of the whole at the end.
    ETL_UINT32            uViolations = 0;
    bool                bTruncated = false;

    SDialectViolation    aViolations[ kDialectMaxViolations ];
};

The result of a check.

function

CheckDialect

Ethereal::Ai::Schema#
EStatus CheckDialect( const CSchemaDocument & Document, EDialect eDialect, SDialectReport & Report ) noexcept;

Lists what eDialect would refuse in the schema.

Looks at every node of the document, used or not. A schema read in lenient mode may hold keywords the module ignored: each one is a warning, because the check could not look at it.

Document
The schema read.
eDialect
The dialect. eGeneric reports only the ignored keywords.
Report
Receives the result.
Report.eStatus.
function

CheckDialect

Ethereal::Ai::Schema#
EStatus CheckDialect( const CSchema & Schema, EDialect eDialect, SDialectReport & Report ) noexcept;

CheckDialect on the document of a compiled schema.

schema_document.hpp

#include <ethereal/cpp/ai/schema/schema_document.hpp>

CSchemaDocument: a JSON Schema read into a flat, immutable model.

Parse reads the text with the JSON pull reader, without recursion: an explicit stack bounded by the options walks the schemas inside schemas. Every schema (an object or true/false) becomes one SSchemaNode in a flat array, the root first. A node refers to the schemas inside it by index, never by pointer.

After the read, every $ref is resolved to the node it names (only local references, "#" and JSON Pointers into this document), and the graph is checked: a cycle of $ref, allOf, anyOf, oneOf or not that reads no data is an error, because a validation would never end. A cycle that goes through properties or items is a recursive schema (a tree, a list) and is allowed: its nodes carry kNodeRecursive, and the validator bounds them with the depth of the data.

The values a schema holds as data (const, enum, default and the items of examples) stay as raw JSON text: views into the copy of the text that the document keeps. Strings the module needs decoded (property names, required, pattern, title, description, $ref) are decoded once, at the read.

This is the model only. CSchema (schema_validator.hpp) compiles it into a validation program.

The document is immutable after Parse and may be read by many threads at once. Parse itself is for one thread.

const

kNoNode

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNoNode = 0xFFFFFFFFu;

No node: an absent keyword, or the parent of the root.

const

kNodeTrue

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeTrue = 0x00000001u;

Bits of SSchemaNode::uFlags.

const

kNodeFalse

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeFalse = 0x00000002u;

the schema 'false'

const

kNodeRecursive

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeRecursive = 0x00000004u;

on a cycle through data

const

kNodeHasMinimum

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMinimum = 0x00000010u;
const

kNodeHasMaximum

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMaximum = 0x00000020u;
const

kNodeHasExclusiveMinimum

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasExclusiveMinimum = 0x00000040u;
const

kNodeHasExclusiveMaximum

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasExclusiveMaximum = 0x00000080u;
const

kNodeHasMultipleOf

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMultipleOf = 0x00000100u;
const

kNodeHasMinLength

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMinLength = 0x00000200u;
const

kNodeHasMaxLength

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMaxLength = 0x00000400u;
const

kNodeHasMinItems

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMinItems = 0x00000800u;
const

kNodeHasMaxItems

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasMaxItems = 0x00001000u;
const

kNodeHasPattern

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasPattern = 0x00002000u;
const

kNodeHasEnum

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasEnum = 0x00004000u;
const

kNodeHasConst

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasConst = 0x00008000u;
const

kNodeHasDefault

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasDefault = 0x00010000u;
const

kNodeHasRequired

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasRequired = 0x00020000u;
const

kNodeHasProperties

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasProperties = 0x00040000u;
const

kNodeHasExamples

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeHasExamples = 0x00080000u;
const

kNodeUniqueItems

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeUniqueItems = 0x00100000u;
const

kNodeDefsAsDefinitions

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeDefsAsDefinitions = 0x00200000u;

Defs came as 'definitions'

const

kNodeItemsFromArray

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kNodeItemsFromArray = 0x00400000u;

lenient: draft 7 items array

struct

SSchemaRange

Ethereal::Ai::Schema#
C++
struct   SSchemaRange
{
    /// @brief  First element.
    ETL_UINT32        uFirst = 0;

    /// @brief  Number of elements.
    ETL_UINT32        uCount = 0;
};
struct

SSchemaNumber

Ethereal::Ai::Schema#
C++
struct   SSchemaNumber
{
    /// @brief  The nearest double.
    ETL_DOUBLE            dValue = 0.0;

    /// @brief  The text, exactly as in the schema (a view into the document's copy).
    std::string_view    sText;
};

A number of the schema, with its text.

struct

SSchemaProperty

Ethereal::Ai::Schema#
C++
struct   SSchemaProperty
{
    /// @brief  The name, decoded.
    std::string_view    sName;

    /// @brief  The schema.
    ETL_UINT32            uNode = kNoNode;
};

A name and the schema under it (properties, $defs).

struct

SSchemaNode

Ethereal::Ai::Schema#
C++
struct   SSchemaNode
{
    /// @brief  The schema that holds this one, kNoNode for the root.
    ETL_UINT32            uParent = kNoNode;

    /// @brief  The keyword of the parent this schema is under.
    EKeyword            eEdge = EKeyword::eNone;

    /// @brief  'type' as kType* bits. Zero when there is no 'type'.
    ETL_UINT8            uTypes = 0;

    /// @brief  'format', eNone when absent.
    EFormat                eFormat = EFormat::eNone;

    /// @brief  Under properties or $defs: the name. Empty otherwise.
    std::string_view    sEdgeName;

    /// @brief  Under prefixItems, allOf, anyOf or oneOf: the index. Zero otherwise.
    ETL_UINT32            uEdgeIndex = 0;

    /// @brief  kNode* bits.
    ETL_UINT32            uFlags = 0;

    /// @brief  Where the schema starts in the text.
    std::size_t            uOffset = 0;

    /// @brief  The numbers (valid when their kNodeHas* bit is set).
    SSchemaNumber        Minimum;
    SSchemaNumber        Maximum;
    SSchemaNumber        ExclusiveMinimum;
    SSchemaNumber        ExclusiveMaximum;
    SSchemaNumber        MultipleOf;

    /// @brief  Lengths in code points, counts of items.
    ETL_UINT64            uMinLength = 0;
    ETL_UINT64            uMaxLength = 0;
    ETL_UINT64            uMinItems = 0;
    ETL_UINT64            uMaxItems = 0;

    /// @brief  'pattern', decoded, in ECMA-262 syntax as written.
    std::string_view    sPattern;

    /// @brief  'properties' and '$defs' (Properties).
    SSchemaRange        Properties;
    SSchemaRange        Defs;

    /// @brief  'required' (Names).
    SSchemaRange        Required;

    /// @brief  'prefixItems', 'allOf', 'anyOf', 'oneOf' (Children).
    SSchemaRange        PrefixItems;
    SSchemaRange        AllOf;
    SSchemaRange        AnyOf;
    SSchemaRange        OneOf;

    /// @brief  'enum' and 'examples' (Values, raw JSON).
    SSchemaRange        Enum;
    SSchemaRange        Examples;

    /// @brief  'items', 'additionalProperties', 'not'.
    ETL_UINT32            uItems = kNoNode;
    ETL_UINT32            uAdditionalProperties = kNoNode;
    ETL_UINT32            uNot = kNoNode;

    /// @brief  '$ref' decoded, and the node it names.
    std::string_view    sRef;
    ETL_UINT32            uRefTarget = kNoNode;

    /// @brief  'const' and 'default', raw JSON.
    std::string_view    sConst;
    std::string_view    sDefault;

    /// @brief  'title' and 'description', decoded.
    std::string_view    sTitle;
    std::string_view    sDescription;
};

One schema of the document.

The lists live in arrays of the document, read through its accessors (Properties, Children, Names, Values). An absent keyword has an empty range, kNoNode, an empty view or its flag cleared.

class

CSchemaDocument

Ethereal::Ai::Schema#

A schema read into the model.

class CSchemaDocument

Empty after construction and after Reset. Parse replaces the content. Movable, not copyable.

constructor

CSchemaDocument

#
CSchemaDocument() noexcept = default;

An empty document.

constructor

CSchemaDocument

#
CSchemaDocument( CSchemaDocument && o ) noexcept;

Takes the content of o, which is left empty.

operator

operator=

#
CSchemaDocument & operator=( CSchemaDocument && o ) noexcept;

Frees this content and takes the one of o, which is left empty.

function

Parse

#
EStatus Parse( std::string_view sText, const SParseOptions & Options = {}, SSchemaError * pError = nullptr ) noexcept;

Reads a schema.

The text is copied: it may be freed after the call. On error the document is left empty and pError says what and where.

sText
The schema, UTF-8 JSON.
Options
Mode and limits.
pError
Receives the error. May be null.
eOk or the error status.
function

Reset

#
void Reset( void ) noexcept;

Frees everything. The document is empty.

function

IsEmpty

#
bool IsEmpty( void ) const noexcept

Whether nothing was parsed.

function

Mode

#
EMode Mode( void ) const noexcept

The mode of the parse.

function

Allocator

#
Memory::IAllocator * Allocator( void ) const noexcept

The allocator of the content. Null when empty.

function

Text

#
std::string_view Text( void ) const noexcept

The copy of the text. The raw views point into it.

function

NodeCount

#
ETL_UINT32 NodeCount( void ) const noexcept

Number of schemas. The root is node 0.

function

Node

#
const SSchemaNode & Node( ETL_UINT32 uNode ) const noexcept

A schema, uNode below NodeCount.

function

Root

#
const SSchemaNode & Root( void ) const noexcept

The root schema. The document must not be empty.

function

Properties

#
std::span< const SSchemaProperty > Properties( SSchemaRange Range ) const noexcept

The names and schemas of a range of 'properties' or '$defs'.

function

Children

#
std::span< const ETL_UINT32 > Children( SSchemaRange Range ) const noexcept

The schemas of a range of 'prefixItems', 'allOf', 'anyOf' or 'oneOf'.

function

Names

#
std::span< const std::string_view > Names( SSchemaRange Range ) const noexcept

The names of a range of 'required'.

function

Values

#
std::span< const std::string_view > Values( SSchemaRange Range ) const noexcept

The raw JSON values of a range of 'enum' or 'examples'.

function

Warnings

#
std::span< const SSchemaWarning > Warnings( void ) const noexcept

What lenient mode ignored, in the order of the text.

function

PointerOf

#
std::size_t PointerOf( ETL_UINT32 uNode, std::span< char > Out ) const noexcept;

Writes the JSON Pointer of a schema ("/properties/city"), zero terminated.

uNode
The schema.
Out
Destination. Cut short when too small.
The size of the whole pointer, without the zero (larger than Out when it was cut).
function

Resolve

#
ETL_UINT32 Resolve( std::string_view sRef ) const noexcept;

The schema a local reference names ("#", "#/$defs/a").

The fragment is percent-decoded, then read as a JSON Pointer whose segments follow the keywords that hold schemas.

sRef
The reference, decoded from JSON.
The node, or kNoNode when the reference names no schema here.

schema_perfect.hpp

#include <ethereal/cpp/ai/schema/schema_perfect.hpp>

The perfect hash of the decoder and of the validator: the field names and the enum names of a described type, built at compile time, and the enum candidates of a compiled schema, built when the schema compiles.

A name becomes a 64 bit key from its length and two loads of at most 8 bytes (the first and the last bytes, overlapping when the name is short). Up to 16 bytes the loads see every byte, so two different names of that size only share a key by a collision of the mix. Longer names that agree on the first and last 8 bytes share a key, and the table is then not built (the caller compares names one by one).

The table is "hash and displace": the key picks a bucket (about two keys each), the bucket keeps a displacement, and the key with the displacement picks a slot (twice as many slots as keys). The builder tries displacements, largest bucket first, until every key of the bucket lands on a free slot. A lookup is two multiplications and two loads, and the caller confirms the name of the slot.

Internal to the module (Detail): the layout may change.

schema_repair.hpp

#include <ethereal/cpp/ai/schema/schema_repair.hpp>

Extraction and repair of the JSON a model writes: the first document out of prose and Markdown fences, and a limited, audited repair that never invents content.

Extract finds the first object or array in a text. Repair fixes, in one pass and with no allocation, only these defects:

  • a truncated document: an open string is closed, open arrays and objects are closed, a comma left at the end is dropped;
  • a trailing comma before ']' or '}';
  • single quotes around a string or a key;
  • a key without quotes (letters, digits, '_' and '$');
  • comments, '//' to the end of the line and '/ ... /';
  • the Python literals True, False and None;
  • invalid escapes: "\'" is an apostrophe, "\xHH" the character U+00HH, any other one keeps its backslash as text ("\d" becomes "\\d"), and a raw control character in a string is escaped;
  • a byte order mark before the document.

Every change goes to the log with its kind and its position in the input. What would need content the model did not write fails: a value missing after ':', a key cut in the middle, a literal or an escape cut in the middle, a number that ended in '-', '.' or 'e', NaN, Infinity, a hexadecimal number, a lone surrogate, a missing colon or comma.

enum

ERepairMode

Ethereal::Ai::Schema#
C++
enum class   ERepairMode : ETL_UINT8
{
    /// @brief  Nothing: the document has to be valid JSON already. The output is the
    ///             input.
    eStrict = 0,

    /// @brief  The defects of the list in the header.
    eTolerant
};

How much Repair may change.

enum

ERepairEdit

Ethereal::Ai::Schema#
C++
enum class   ERepairEdit : ETL_UINT8
{
    eRemoveBom = 0,            /// The byte order mark before the document.
    eRemoveComment,            /// A comment.
    eRemoveTrailingComma,    /// A comma before ']' or '}', or one left by a truncation.
    eSingleQuotes,            /// A string or key in single quotes, written in double quotes.
    eQuoteKey,                /// A key without quotes, quoted.
    ePythonLiteral,            /// True, False or None.
    eFixEscape,                /// An invalid escape, or a raw control character in a string.
    eCloseString,            /// The string the input ended in, closed.
    eCloseContainer            /// An array or object the input ended in, closed.
};

The kind of one change.

function

RepairEditName

Ethereal::Ai::Schema#
const char * RepairEditName( ERepairEdit eEdit ) noexcept;

The name of a kind of change ("trailing-comma"). Never null.

struct

SRepairEdit

Ethereal::Ai::Schema#
C++
struct   SRepairEdit
{
    ERepairEdit        eEdit = ERepairEdit::eRemoveComment;

    /// @brief  Where it is in the input (for a closing, the end of the input).
    std::size_t        uOffset = 0;

    /// @brief  Bytes of the input it removes or replaces (0 for a closing).
    std::size_t        uLength = 0;
};

One change.

const

kRepairMaxEdits

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kRepairMaxEdits = 64u;

Most changes a log holds. The count goes on beyond it.

struct

SRepairLog

Ethereal::Ai::Schema#
C++
struct   SRepairLog
{
    /// @brief  The changes, all of them counted.
    ETL_UINT32        uEdits = 0;
    bool            bTruncated = false;
    SRepairEdit        aEdits[ kRepairMaxEdits ];

    /// @brief  With a failure: where in the input, and why (static, in English).
    std::size_t        uErrorOffset = 0;
    const char *    pMessage = "";
};

What Repair did.

function

Extract

Ethereal::Ai::Schema#
EStatus Extract( std::string_view sText, std::size_t * pBegin, std::size_t * pEnd ) noexcept;

Finds the first JSON object or array in a text.

Prose before and after and Markdown fences are skipped. A '{' or '[' counts only when what follows looks like JSON (a key, a value or the end), so a brace in the prose is not taken. The end is the matching bracket, found with strings, single quoted ones and comments in mind. A document the text ends in before it closes runs to the end of the text (or of its fence), for Repair to close.

sText
The text.
pBegin
Receives where the document starts.
pEnd
Receives where it ends (one past the last byte).
eOk, eJsonSyntax (no document), eInvalidArgument or eNotLicensed.
function

Repair

Ethereal::Ai::Schema#
EStatus Repair( std::string_view sInput, ERepairMode eMode, std::span< char > Out, std::size_t * pWritten, SRepairLog & Log ) noexcept;

Writes the document as valid JSON, with only the changes of the list.

The output keeps the text of the input, its white space included, and changes only what the log lists. Repairing the output again changes nothing. Nothing after the document is accepted: call Extract first when the text may have prose. No allocation. Nesting up to 512.

sInput
The document.
eMode
eStrict accepts no change, eTolerant the list.
Out
Destination. May be empty, to measure.
pWritten
Receives the size of the output. With eBufferTooSmall, a size that is enough (a few bytes above the final one, at most).
Log
Receives the changes, or the failure.
eOk, eJsonSyntax (it cannot be repaired without inventing content, or a change was needed in eStrict: Log says where and why), eDepthLimit, eBufferTooSmall, eInvalidArgument or eNotLicensed.

schema_types.hpp

#include <ethereal/cpp/ai/schema/schema_types.hpp>

Vocabulary of the Ai::Schema module: status, modes, keywords, types, formats, parse limits and the parse error.

The schemas come from outside the program (a provider, an MCP server, a file) and are untrusted input. Every limit has a safe default, and a hostile schema gives an error, never a crash, a deep recursion or a huge allocation.

The module reads the subset of JSON Schema draft 2020-12 that the LLM providers and MCP use. A keyword outside it is an error in strict mode and is ignored, with a warning, in lenient mode.

enum

EStatus

Ethereal::Ai::Schema#
C++
enum class   EStatus : ETL_UINT32
{
    /// @brief  Success.
    eOk = 0,

    /// @brief  An argument is null, empty or out of range.
    eInvalidArgument,

    /// @brief  The text is not valid JSON. SSchemaError::eJson says why.
    eJsonSyntax,

    /// @brief  Valid JSON, but not a valid schema: a keyword with a value of the wrong
    ///             type, a negative length, a repeated keyword or property, an empty
    ///             anyOf.
    eInvalidSchema,

    /// @brief  Strict mode: a keyword outside the subset of the module, or one that
    ///             JSON Schema 2020-12 does not have. SSchemaError::aKeyword names it.
    eUnsupportedKeyword,

    /// @brief  A form the module does not handle inside a keyword it has: a remote
    ///             $ref, a $ref to an anchor, $id below the root, $schema of another draft
    ///             or a format outside the list (strict), items as an array (strict).
    eUnsupportedFeature,

    /// @brief  A $ref whose target is not a schema of this document.
    eRefNotFound,

    /// @brief  A cycle of $ref, allOf, anyOf, oneOf or not that reads no data: the
    ///             validation would never end.
    eRefCycle,

    /// @brief  Schemas nested deeper than SParseOptions::uMaxDepth, or combinators
    ///             deeper than SParseOptions::uMaxCombinatorDepth.
    eDepthLimit,

    /// @brief  More schemas than SParseOptions::uMaxNodes, or a text longer than
    ///             SParseOptions::uMaxDocumentBytes.
    eLimitExceeded,

    /// @brief  The allocator returned null.
    eOutOfMemory,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///             ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief  The caller's buffer is too small (Encode says the size needed).
    eBufferTooSmall
};

Result of a schema operation.

function

StatusName

Ethereal::Ai::Schema#
const char * StatusName( EStatus eStatus ) noexcept;

Name of a status, for messages. Never returns null.

enum

EMode

Ethereal::Ai::Schema#
C++
enum class   EMode : ETL_UINT8
{
    /// @brief  A keyword outside the subset is an error.
    eStrict = 0,

    /// @brief  A keyword outside the subset is ignored and recorded as a warning.
    ///             What would change the meaning of the rest of the document (a remote
    ///             $ref, $id below the root) is still an error.
    eLenient
};

How a schema is read.

enum

EKeyword

Ethereal::Ai::Schema#
C++
enum class   EKeyword : ETL_UINT8
{
    /// @brief  None: the root, or a keyword the module ignored.
    eNone = 0,

    eType,
    eProperties,
    eRequired,
    eAdditionalProperties,
    eItems,
    ePrefixItems,
    eEnum,
    eConst,
    eAnyOf,
    eOneOf,
    eAllOf,
    eNot,
    eRef,
    eDefs,

    /// @brief  'definitions', the draft 7 name of $defs, read the same way.
    eDefinitions,

    eMinimum,
    eMaximum,
    eExclusiveMinimum,
    eExclusiveMaximum,
    eMultipleOf,
    eMinLength,
    eMaxLength,
    ePattern,
    eFormat,
    eMinItems,
    eMaxItems,
    eUniqueItems,
    eTitle,
    eDescription,
    eDefault,
    eExamples,

    /// @brief  '$schema', only at the root.
    eSchema,

    /// @brief  '$id', only at the root.
    eId,

    /// @brief  '$comment', 'deprecated', 'readOnly' and 'writeOnly': annotations that
    ///             change no validation, accepted and dropped.
    eIgnoredAnnotation,

    /// @brief  Number of keywords. Not a keyword.
    eCount
};

The keywords the module reads. Also the edge from a schema to the schema inside it (SSchemaNode::eEdge).

function

KeywordName

Ethereal::Ai::Schema#
const char * KeywordName( EKeyword eKeyword ) noexcept;

The keyword as written in a schema ("additionalProperties"). Never null. eIgnoredAnnotation gives "$comment", eNone and eCount give "".

const

kTypeNull

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeNull = 0x01u;

Bits of SSchemaNode::uTypes, one per JSON Schema type.

const

kTypeBoolean

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeBoolean = 0x02u;
const

kTypeObject

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeObject = 0x04u;
const

kTypeArray

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeArray = 0x08u;
const

kTypeNumber

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeNumber = 0x10u;
const

kTypeString

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeString = 0x20u;
const

kTypeInteger

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeInteger = 0x40u;

'integer': a number with no fraction ('1.0' included, as 2020-12 says).

const

kTypeAll

Ethereal::Ai::Schema#
inline constexpr ETL_UINT8 kTypeAll = 0x7Fu;

Every type.

enum

EFormat

Ethereal::Ai::Schema#
C++
enum class   EFormat : ETL_UINT8
{
    /// @brief  No format, or one ignored in lenient mode.
    eNone = 0,

    /// @brief  RFC 3339 'date-time'.
    eDateTime,

    /// @brief  RFC 3339 'full-date'.
    eDate,

    /// @brief  RFC 3339 'full-time'.
    eTime,

    /// @brief  ISO 8601 duration ('P3DT4H').
    eDuration,

    /// @brief  'email', the simple form documented by the validator.
    eEmail,

    /// @brief  RFC 1123 host name.
    eHostname,

    /// @brief  RFC 3986 absolute URI.
    eUri,

    /// @brief  RFC 4122 'uuid', with hyphens.
    eUuid,

    /// @brief  Dotted IPv4.
    eIpv4,

    /// @brief  RFC 4291 IPv6.
    eIpv6
};

The formats the module knows.

function

FormatName

Ethereal::Ai::Schema#
const char * FormatName( EFormat eFormat ) noexcept;

The format as written ("date-time"). Never null, "" for eNone.

const

kSchemaMaxDepthLimit

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kSchemaMaxDepthLimit = 1024u;

Highest value accepted for SParseOptions::uMaxDepth and uMaxJsonDepth.

struct

SParseOptions

Ethereal::Ai::Schema#
C++
struct   SParseOptions
{
    /// @brief  Strict or lenient.
    EMode                eMode = EMode::eStrict;

    /// @brief  Schemas inside schemas, the root at depth 1. Up to kSchemaMaxDepthLimit.
    ETL_UINT32            uMaxDepth = 64u;

    /// @brief  anyOf, oneOf, allOf and not inside one another, as written.
    ETL_UINT32            uMaxCombinatorDepth = 16u;

    /// @brief  JSON nesting of the text, the values of const, enum and default
    ///             included. Up to kSchemaMaxDepthLimit.
    ETL_UINT32            uMaxJsonDepth = 256u;

    /// @brief  Schemas in the document (each object or boolean that is a schema).
    ETL_UINT32            uMaxNodes = 65536u;

    /// @brief  Size of the text.
    std::size_t            uMaxDocumentBytes = std::size_t( 4u ) << 20;

    /// @brief  Allocator of the document. Null is Memory::DefaultAllocator.
    Memory::IAllocator *    pAllocator = nullptr;
};

Options of CSchemaDocument::Parse. The defaults are safe for a schema from the network.

const

kSchemaPointerBytes

Ethereal::Ai::Schema#
inline constexpr std::size_t kSchemaPointerBytes = 256u;

Bytes of SSchemaError::aPointer, terminating zero included.

struct

SSchemaError

Ethereal::Ai::Schema#
C++
struct   SSchemaError
{
    /// @brief  The status. eOk when there is no error.
    EStatus                                eStatus = EStatus::eOk;

    /// @brief  For eJsonSyntax, the status of the JSON reader. eOk otherwise.
    Serialization::Json::EJsonStatus    eJson = Serialization::Json::EJsonStatus::eOk;

    /// @brief  Where in the text: byte offset from 0, line and column (bytes) from 1.
    std::size_t                            uOffset = 0;
    std::size_t                            uLine = 1;
    std::size_t                            uColumn = 1;

    /// @brief  JSON Pointer (RFC 6901) of the place in the schema, zero terminated. Empty
    ///             for the root. Cut short when it does not fit (bPointerTruncated).
    char                                aPointer[ kSchemaPointerBytes ] = {};

    /// @brief  Whether aPointer misses its last segments.
    bool                                bPointerTruncated = false;

    /// @brief  The keyword involved, zero terminated, or empty. For an unknown keyword,
    ///             its name as written, cut at 63 bytes.
    char                                aKeyword[ 64 ] = {};

    /// @brief  Static message, in English, short enough for a model to read.
    const char *                        pMessage = "";
};

Why a parse failed, and where.

struct

SSchemaWarning

Ethereal::Ai::Schema#
C++
struct   SSchemaWarning
{
    /// @brief  The schema where it was (CSchemaDocument::Node).
    ETL_UINT32            uNode = 0;

    /// @brief  Byte offset of the keyword in the text.
    std::size_t            uOffset = 0;

    /// @brief  The keyword as written, raw (a view into CSchemaDocument::Text).
    std::string_view    sKeyword;

    /// @brief  Static message, in English.
    const char *        pMessage = "";
};

Something ignored in lenient mode.

schema_validator.hpp

#include <ethereal/cpp/ai/schema/schema_validator.hpp>

CSchema, a schema compiled into a flat validation program, and CValidator, which checks JSON against it from the events of the pull reader, without a DOM.

Compile reads the schema (CSchemaDocument) and turns every node into a record of tables: the property names sorted for a binary search, the numbers as exact decimals, the values of enum and const in a canonical form, the patterns translated from ECMA-262 to the Regex module and compiled. Nothing of the program is recursive.

The validator follows the events of the JSON reader. For each value it keeps the list of schemas that apply to it (frames): the root, the schema of a property or an item, and what $ref, allOf, anyOf, oneOf and not bring in. anyOf, oneOf and not run their branches side by side, each in a context of its own, and decide when the value ends. No recursion: an explicit stack of levels, one per depth of the instance, bounded by the options.

Equality (const, enum, uniqueItems) is the one of JSON Schema: numbers by value ('1' equals '1.0'), objects without regard to the order of the keys. The numbers are compared as exact decimals, never through a double: a bignum keeps every digit.

A CSchema is immutable after Compile and may be shared by many threads. A CValidator is for one thread, and keeps its memory from one document to the next: after the first documents, a validation allocates nothing.

struct

SCompileOptions

Ethereal::Ai::Schema#
C++
struct   SCompileOptions
{
    /// @brief  How the text is read (mode, limits, allocator).
    SParseOptions        Parse;

    /// @brief  Whether 'format' is checked. JSON Schema 2020-12 makes it an annotation
    ///             by default. The providers of LLM check it in structured outputs, so the
    ///             module checks it unless told otherwise.
    bool                bAssertFormat = true;

    /// @brief  Ceiling of the compiled program of one 'pattern' (see
    ///             Regex::SRegexOptions::uMaxProgramBytes).
    std::size_t            uMaxPatternBytes = std::size_t( 1u ) << 20;
};

Options of CSchema::Compile.

class

CSchema

Ethereal::Ai::Schema#

A schema compiled into a validation program.

class CSchema

Empty after construction and after Reset. Movable, not copyable.

constructor

CSchema

#
CSchema() noexcept = default;

An empty schema.

constructor

CSchema

#
CSchema( CSchema && o ) noexcept;

Takes the program of o, which is left empty.

operator

operator=

#
CSchema & operator=( CSchema && o ) noexcept;

Frees this program and takes the one of o, which is left empty.

function

Compile

#
static EStatus Compile( std::string_view sText, const SCompileOptions & Options, CSchema * pOut, SSchemaError * pError = nullptr ) noexcept;

Reads and compiles a schema.

The errors of the read are those of CSchemaDocument::Parse. The compile adds the patterns: one that is not valid ECMA-262 is eInvalidSchema, one with a construct the module does not run (lookaround, a backreference) is eUnsupportedFeature, both with the pointer of the pattern. On error pOut is left empty.

sText
The schema, UTF-8 JSON.
Options
Read and compile options.
pOut
Receives the program.
pError
Receives the error. May be null.
eOk or the error status.
function

Compile

#
static EStatus Compile( CSchemaDocument && Document, const SCompileOptions & Options, CSchema * pOut, SSchemaError * pError = nullptr ) noexcept;

Compiles a schema already read. The document moves into the program.

Document
The schema read. Left empty, success or not.
Options
Compile options (Parse.pAllocator is not used: the program takes the allocator of the document).
pOut
Receives the program.
pError
Receives the error. May be null.
eOk or the error status.
function

Reset

#
void Reset( void ) noexcept;

Frees everything. The schema is empty.

function

IsEmpty

#
bool IsEmpty( void ) const noexcept

Whether nothing was compiled.

function

Document

#
const CSchemaDocument & Document( void ) const noexcept

The document the program came from: the nodes, their pointers, the annotations (title, description, default, examples).

function

AssertsFormat

#
bool AssertsFormat( void ) const noexcept;

Whether 'format' is checked (SCompileOptions::bAssertFormat).

const

kValidationMaxErrors

Ethereal::Ai::Schema#
inline constexpr ETL_UINT32 kValidationMaxErrors = 16u;

Most errors a report holds.

struct

SValidateOptions

Ethereal::Ai::Schema#
C++
struct   SValidateOptions
{
    /// @brief  The validation stops after this many errors, from 1 (the default: the
    ///             first error) to kValidationMaxErrors.
    ETL_UINT32            uMaxErrors = 1u;

    /// @brief  Nesting of the instance, up to kSchemaMaxDepthLimit. Deeper is
    ///             eDepthLimit.
    ETL_UINT32            uMaxDepth = 256u;

    /// @brief  Schemas applied at the same time, summed over the open levels. A
    ///             recursive schema with anyOf at each level multiplies them: going over
    ///             is eLimitExceeded, never a huge allocation.
    ETL_UINT32            uMaxFrames = 65536u;

    /// @brief  Size of the instance (the sum of the pieces, when streaming).
    std::size_t            uMaxDocumentBytes = std::size_t( 64u ) << 20;

    /// @brief  Allocator of the validator. Null is Memory::DefaultAllocator.
    Memory::IAllocator *    pAllocator = nullptr;
};

Options of a validation. The defaults are safe for input from the network.

struct

SValidationError

Ethereal::Ai::Schema#
C++
struct   SValidationError
{
    /// @brief  The keyword broken. eNone for the schema 'false'.
    EKeyword            eKeyword = EKeyword::eNone;

    /// @brief  The schema node that has the keyword (CSchemaDocument::Node, PointerOf).
    ETL_UINT32            uSchemaNode = kNoNode;

    /// @brief  Byte offset in the instance: the value, or the key for a property that
    ///             is not allowed.
    std::size_t            uOffset = 0;

    /// @brief  JSON Pointer of the place in the instance, zero terminated. Empty for the
    ///             root. Cut short when it does not fit (bPointerTruncated).
    char                aPointer[ kSchemaPointerBytes ] = {};

    /// @brief  Whether aPointer misses its last segments.
    bool                bPointerTruncated = false;

    /// @brief  What the keyword asked for, when it helps to fix the value: the missing
    ///             property of 'required', the limit of 'minimum', the pattern, the format,
    ///             the types of 'type'. A view into the CSchema, valid while it lives.
    std::string_view    sDetail;

    /// @brief  Static message, in English, short enough for a model to read.
    const char *        pMessage = "";
};

One place where the instance breaks the schema.

struct

SValidationReport

Ethereal::Ai::Schema#
C++
struct   SValidationReport
{
    /// @brief  eOk when the validation ran to a verdict. Otherwise why it could not:
    ///             eJsonSyntax (the instance is not JSON, see Json), eDepthLimit,
    ///             eLimitExceeded (the document or the frames), eOutOfMemory,
    ///             eInvalidArgument, eNotLicensed.
    EStatus                                eStatus = EStatus::eOk;

    /// @brief  The verdict: eStatus is eOk and no error was found.
    bool                                bValid = false;

    /// @brief  Errors in aErrors, in the order found.
    ETL_UINT32                            uErrors = 0;

    /// @brief  Whether the validation stopped at SValidateOptions::uMaxErrors with the
    ///             rest of the instance not checked.
    bool                                bStoppedEarly = false;

    /// @brief  Static message for eStatus, in English. Empty with eOk.
    const char *                        pMessage = "";

    /// @brief  With eJsonSyntax, the error of the reader.
    Serialization::Json::SJsonError        Json;

    /// @brief  The errors. Only the first uErrors are written: the entries after them
    ///             keep whatever they held.
    SValidationError                    aErrors[ kValidationMaxErrors ];
};

The result of a validation.

enum

EPrefixState

Ethereal::Ai::Schema#
C++
enum class   EPrefixState : ETL_UINT8
{
    eViable = 0,    /// Nothing so far rules out a valid document.
    eComplete,        /// The root value is complete and valid. Only white space may follow.
    eInvalid,        /// The document cannot be valid any more (see PrefixError and End).
};

What the pieces given so far say about the document (prefix mode).

eInvalid is certain: no rest of the document makes it valid, and the report of End will not be valid. eViable is not a promise: it only says that nothing found so far rules a valid document out. Which breaks are found before their value is complete is listed in CValidator::Feed.

class

CValidator

Ethereal::Ai::Schema#

Validates JSON against a CSchema, whole or in pieces.

class CValidator

Whole: Validate. In pieces: Begin, Feed each piece as it arrives (any size, one byte included), End. Both give the same report.

In pieces, each Feed also says whether the document can still be valid (EPrefixState): a caller that streams the output of a model stops it as soon as it went wrong.

Movable, not copyable. For the exclusive use of one thread.

constructor

CValidator

#
CValidator() noexcept = default;

A validator with the default options.

constructor

CValidator

#
explicit CValidator( const SValidateOptions & Options ) noexcept;

A validator with these options.

constructor

CValidator

#
CValidator( CValidator && o ) noexcept;

Takes the state of o, which is left without one.

operator

operator=

#
CValidator & operator=( CValidator && o ) noexcept;

Frees this state and takes the one of o.

function

Validate

#
EStatus Validate( const CSchema & Schema, std::string_view sJson, SValidationReport & Report ) noexcept;

Validates a whole document.

Schema
The compiled schema. Must outlive the report (its views).
sJson
The instance, UTF-8.
Report
Receives the result.
Report.eStatus.
function

Begin

#
EStatus Begin( const CSchema & Schema ) noexcept;

Starts a document in pieces.

Schema
The compiled schema. Must outlive the validation and the report.
eOk, eInvalidArgument (empty schema, bad options), eOutOfMemory or eNotLicensed.
function

Feed

#
EStatus Feed( std::string_view sPiece, bool bLast = false, EPrefixState * pState = nullptr ) noexcept;

Gives the next piece and checks what it completes.

The piece only needs to live during the call. After a stop (the maximum of errors, a syntax error), the next pieces are ignored.

pState receives what the document so far allows. A break is found at the first byte that decides it, even with its value still cut by the end of the piece:

  • 'type', and enum or const with no candidate of that type: the first byte of the value;
  • a property that additionalProperties false refuses: the first byte of the key that no property name continues;
  • maxLength: the code point that passes it;
  • enum or const of strings: the first byte that no candidate string continues;
  • maxItems, and an item that items or prefixItems refuse: the first byte of the item;
  • anyOf and oneOf: as soon as every branch is certain to fail;
  • the rest (minLength, pattern, format, the numbers, required, minItems, uniqueItems, not, oneOf with two branches valid): when the value is complete.

The report of End does not depend on how the document was cut: a break found early is reported when its value is complete, as Validate does.

sPiece
The piece. May be empty.
bLast
Whether it is the last piece.
pState
Receives the state of the prefix. May be null.
eOk while the validation can go on (even with errors in the instance), or the status that stopped it.
function

PrefixState

#
EPrefixState PrefixState( void ) const noexcept;

The state of the document given so far (see Feed).

eInvalid also when a status stopped the validation (syntax, limits, memory): End will not give a valid report either. eViable before Begin.

function

PrefixError

#
const SValidationError * PrefixError( void ) const noexcept;

The first break that made the prefix eInvalid, for a message to the model that wrote it.

Found early, the break is not in the report yet: End of a document left incomplete only says it is incomplete. The pointer is where the break is: the value, the object of a property not allowed, the value of an anyOf whose branches all fail. Valid until the next Begin or Validate.

The break, or null when the prefix is not eInvalid by the schema (it may be eInvalid by a status: see the return of Feed).
function

End

#
EStatus End( SValidationReport & Report ) noexcept;

Ends the document and gives the report.

Without the last piece (bLast), the document is incomplete: eJsonSyntax with eUnexpectedEnd, unless the validation had already stopped.

Report
Receives the result.
Report.eStatus.
function

Options

#
const SValidateOptions & Options( void ) const noexcept

The options in use.

function

Validate

Ethereal::Ai::Schema#
EStatus Validate( const CSchema & Schema, std::string_view sJson, SValidationReport & Report, const SValidateOptions & Options = {} ) noexcept;

Validates a whole document with a validator of its own.

The validator allocates on each call. To validate many documents, keep a CValidator.

Schema
The compiled schema.
sJson
The instance, UTF-8.
Report
Receives the result.
Options
Options of the validation.
Report.eStatus.