pyxsd.relaxng ============= .. py:module:: pyxsd.relaxng .. autoapi-nested-parse:: Native RELAX NG 1.0 support. The package exposes its public contracts as each stage lands. It does not re-export RELAX NG names from :mod:`pyxsd`, and it never routes RELAX NG work through the XSD compiler. Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/pyxsd/relaxng/comparison/index /autoapi/pyxsd/relaxng/datatypes/index /autoapi/pyxsd/relaxng/introspection/index Attributes ---------- .. autoapisummary:: pyxsd.relaxng.compile Exceptions ---------- .. autoapisummary:: pyxsd.relaxng.AmbiguousValueError pyxsd.relaxng.RelaxNGCompactSyntaxError pyxsd.relaxng.RelaxNGLimitError pyxsd.relaxng.StaleInterpretationError Classes ------- .. autoapisummary:: pyxsd.relaxng.NodeAnnotations pyxsd.relaxng.ScalarAnnotation pyxsd.relaxng.RelaxNGDocument pyxsd.relaxng.CandidateSelection pyxsd.relaxng.RelaxNGComponentDescription pyxsd.relaxng.RelaxNGSchemaDescription pyxsd.relaxng.RelaxNGLimits pyxsd.relaxng.RelaxNGSchema pyxsd.relaxng.RelaxNGElement pyxsd.relaxng.AlternativeValue pyxsd.relaxng.ListInterpretation Functions --------- .. autoapisummary:: pyxsd.relaxng.describe_component pyxsd.relaxng.describe_schema pyxsd.relaxng.find_components pyxsd.relaxng.related_components Package Contents ---------------- .. py:class:: NodeAnnotations Immutable annotation view for one lexical element occurrence. ``patterns`` is the sorted union of surviving authored origins at every scalar and structural site of this element. ``definitions`` names the compiled grammar definitions whose origins intersect those surviving origins. ``scalar`` retains the deterministic typed scalar sites. There is deliberately no singular matched pattern or type. .. py:attribute:: schema_id :type: str .. py:attribute:: revision_id :type: int .. py:attribute:: patterns :type: tuple[pyxsd.relaxng.origins.SourceOrigin, ...] .. py:attribute:: definitions :type: tuple[str, ...] .. py:attribute:: scalar :type: tuple[ScalarAnnotation, ...] .. py:attribute:: complete :type: bool .. py:class:: ScalarAnnotation One typed scalar position on a lexical element. ``kind="text"`` identifies character data at a ``content_index`` in the element's ordered content, including child tails; ``kind="attribute"`` identifies one present attribute by its expanded name. ``value`` retains every surviving candidate; the annotation never selects a preferred branch. .. py:attribute:: kind :type: Literal['text', 'attribute'] .. py:attribute:: name :type: str | None .. py:attribute:: content_index :type: int | None .. py:attribute:: value :type: pyxsd.relaxng.values.AlternativeValue .. py:class:: RelaxNGDocument(schema, root, source, report, *, typed, capture = 'none', limits = None, namespace_context = None, declarations = None, xdm_capture = None, interpretations_current = True, attribute_snapshot = None, binding_evidence = None, annotations = None) One RELAX NG parse revision with its fresh merged report. ``typed`` records whether this parse requested typed access. ``interpretations_current`` reports whether the recorded validation and evidence snapshot still belongs to the current, unedited lexical revision. ``binding_evidence`` is the immutable evidence graph for a valid typed document, or ``None`` for validation-only and invalid typed documents. ``annotations`` is the immutable pattern-annotation table for a valid typed parse requested with ``capture="patterns"``, materialized lazily on first access, and raises an explicit capability error when capture did not run. ``root``, ``report``, and ``source`` keep the lexical tree, the merged schema/instance report, and the original caller source respectively. .. py:attribute:: schema :type: pyxsd.relaxng.schema.RelaxNGSchema .. py:attribute:: root :type: pyxsd.relaxng.tree.RelaxNGElement .. py:attribute:: typed :type: bool .. py:property:: binding_evidence :type: pyxsd.relaxng.evidence.EvidenceGraph | None Internal read-only evidence snapshot for later Phase 3 tasks. This is not a stable public API. It is the immutable graph for a valid typed document and ``None`` for validation-only and invalid typed documents. .. py:property:: interpretations_current :type: bool Whether the validation snapshot still describes the current revision. A dirty revision is not current. A current typed snapshot can also be conservatively marked stale by a transform sharing its revision; both documents then report stale until revalidation. .. py:property:: annotations :type: pyxsd.relaxng.annotations.AnnotationTable Return this parse revision's immutable pattern annotations. Validation-only documents raise an explicit capability error instead of pretending capture ran. A valid typed parse that did not request ``capture="patterns"`` raises the same capability family. An invalid typed document raises :class:`~pyxsd.exceptions.ValidationError` with its report, and an edited or transformed revision raises :class:`~pyxsd.relaxng.errors.StaleInterpretationError` before either validity or capture is considered. Materialization is deferred until this property is read. A valid capture-on parse therefore succeeds whenever a capture-off parse does; a declared datatype decoder failure surfaces here, when annotations are explicitly requested, and is retried on the next access because no table is cached after a failed build. Successful tables are cached for this parse revision. .. py:method:: to_dict(*, typed = True, always_list = False) Returns the current tree as native ``pyxsd`` raw Python values. The RELAX NG adapter owns the grouped representation; ``typed=True`` keeps Python wrappers and raw scalar values, while ``typed=False`` reads lexical text. Typed export requires a valid document whose evidence still describes this lexical revision. ``typed=False`` remains a lexical escape path for dirty and invalid trees. The adapter receives ``mode="raw"``; none of its values are JSON-encoded. .. py:method:: to_data(*, format = 'pyxsd', fidelity = 'best-effort', typed = True, always_list = False) Returns the current tree under a RELAX NG data-format contract. ``format="pyxsd"`` keeps the native grouped representation and converts its scalars to JSON-safe values. The other four formats use their RELAX NG-owned adapters. ``typed`` and ``always_list`` are native-only options, rejected exactly as the XSD document rejects them on another format. Typed schema-directed output requires a valid, current typed document; native ``typed=False`` and JsonML remain lexical escapes over the current tree. The adapter receives ``mode="json-safe"`` for JSON-safe scalar output and later tagging. .. py:method:: to_json(*, indent = None, format = 'pyxsd', fidelity = 'best-effort', typed = True, always_list = False) Returns :meth:`to_data` as standards-compliant JSON text. No fallback serializer is used: non-finite adapter output is rejected by ``allow_nan=False`` instead of emitting a non-JSON token. .. py:method:: to_string() Serialize the current lexical tree, even when typed views are stale. The writer never consults typed evidence or the parse report, so a dirty or transformed typed document, a validation-only document, and an invalid document all retain this lexical escape path. The root tail is outside the document element and is not written. .. py:method:: write(dest) Write the exact lexical serialization to a path or caller file object. Paths are opened and closed here with UTF-8 encoding. Caller file objects are written and flushed but left open, matching the existing path-versus-file ownership convention. Like :meth:`to_string`, this reads the current lexical tree without requiring fresh typed evidence. .. py:method:: revalidate() Validate an independent clone of the current tree. The lexical tree is cloned into a fresh revision, serialized with the schema-neutral writer, and parsed against the same schema with this document's typed, capture, XDM, and instance-limit settings. The result has fresh nodes, a fresh report, fresh evidence or a fresh invalid-document interpretation, fresh annotations when captured, and a new revision ID. Projection classes come from the schema's plan and therefore keep their plan-fixed identity while the nodes are new; candidate IDs stay schema-stable while candidate values are rebuilt. This document, its nodes, report, evidence, and annotations are never refreshed or replaced. Validation-only documents stay validation-only: the result computes no evidence and exposes no annotation view. Typed documents keep capture mode and its independent annotation budget. The parse's XDM request is replayed, including for a transformed root that started without a coherent capture, so the returned document owns a fresh coherent XDM view when capture was requested. Serialization emits the recorded namespace declarations so prefixed QName values keep their external namespace context. The recorded namespace and effective base-URI frames are then restored onto the repared nodes, because a bare string round trip cannot carry a source-relative base URI. A root tail is outside the document element and is not carried into the new document. The lexical writer and ``to_string``/``write`` remain available on the old document and on the result; ``to_dict``, ``to_data``, and ``to_json`` dispatch through the RELAX NG adapter registry and apply its freshness policy. The original DTD declaration evidence is reused without retrieving a DTD or serializing a DOCTYPE. Absent evidence stays absent. Source addresses and XDM capture use the original caller's source identifier, including a named stream's name; anonymous inputs stay anonymous. With a trusted resource policy, an original path read may have supplied a different canonical identifier. Revalidation passes a named stream through the policy parser, not its path reader, so that reader's canonical identifier is not restored. .. py:method:: locate(location) Resolve one parse-specific occurrence to its lexical node. RELAX NG parsing records an exact source address for every lexical node instead of building an XSD binding provenance table. This lookup compares those recorded addresses; it never matches by attribute value, local name, or position in another revision. An attribute address returns the parse-time lexical attribute value from this document's immutable snapshot, so later edits neither change nor create old addresses. An address from another parse is ``missing``. .. py:exception:: AmbiguousValueError No single scalar interpretation is authoritative for a position. Raised by later value interfaces when several schema-defined contracts survive. Callers inspect the alternatives instead of guessing a type. .. py:exception:: RelaxNGCompactSyntaxError(message, *, location = None, found = None, expected = ()) A compact-syntax source could not be read into a schema. Lexical, escape, tokenization, and unrecoverable grammar failures raise this exception. ``location`` is the exact source occurrence when known, ``found`` describes the offending token, and ``expected`` lists the tokens that would have been accepted. The string form starts with ``source:line:column`` when span evidence is available. .. py:property:: location :type: pyxsd.locations.IssueLocation | None The source occurrence where the failure was detected. .. py:property:: found :type: str | None A description of the token that was found, when known. .. py:property:: expected :type: tuple[str, ...] Descriptions of acceptable tokens, sorted deterministically. .. py:exception:: RelaxNGLimitError(stage, budget, configured, observed, *, detail = None) A configured RELAX NG budget was exhausted. Budget exhaustion is not semantic invalidity: a schema or instance that exceeds a caller's budget has no verdict. The attributes name the work that stopped and the observation that crossed the configured value. The compact reader's fixed interpreter-safety nesting ceiling is reported as an exhausted ``max_compact_depth`` budget even when that budget is unset or larger, and ``detail`` explains that effective bound. .. py:property:: stage :type: str The compiler or validator stage that exhausted the budget. .. py:property:: budget :type: str The :class:`~pyxsd.relaxng.limits.RelaxNGLimits` field name. .. py:property:: configured :type: int The caller's configured value for this budget. .. py:property:: observed :type: int The observed count that exceeded the configured value. .. py:exception:: StaleInterpretationError A retained interpretation belongs to an older schema revision. Raised by later value interfaces when freshness is required and a document or annotation was compiled against a schema that has changed. .. py:class:: CandidateSelection Require one contract candidate at one exact parse occurrence. Candidate identity is grammar-scoped; occurrence identity remains parse-local. Equal candidate IDs at distinct sites never collapse these requirements. .. py:attribute:: occurrence :type: EvidenceOccurrence .. py:attribute:: candidate_id :type: str .. py:class:: RelaxNGComponentDescription One immutable component of a compiled RELAX NG grammar. ``kind`` is ``grammar``, ``define``, ``pattern``, ``name-class``, ``datatype``, ``route``, or ``resource``. ``namespace`` is an expanded-name namespace only (never a datatype-library URI). ``name`` is a local name for exact element/attribute patterns and exact name classes, an expanded element name for routes, a datatype type name for datatypes, and the first canonical resource ID for resources; otherwise it is absent. A definition's ``name`` is the composer-generated key. ``synthetic`` is true only for these generated definitions, not for patterns or routes; authored ``define`` names survive only as origins. ``owner_id`` is ``None`` for the grammar and ``"grammar"`` for all other components: it denotes inventory ownership, not an authored parent. ``name_class`` is the canonical presentation of an element/attribute/route/name-class name class. Datatype components carry their normalized library, type, and ordered parameters. There are deliberately no XSD-only fields: no ``global_declaration``, Python binding, occurrence count, or default. Origins union every contributing site. Location is the smallest origin by source ID then source/path/attribute, except resources: their location is the first sorted reference's location (possibly absent), ordered by containing ID, reference, base, xml:base, canonical ID, then location. .. py:attribute:: id :type: str .. py:attribute:: kind :type: str .. py:attribute:: name :type: str | None .. py:attribute:: namespace :type: str | None .. py:attribute:: location :type: pyxsd.locations.IssueLocation | None .. py:attribute:: origins :type: pyxsd.relaxng.origins.OriginTable .. py:attribute:: owner_id :type: str | None .. py:attribute:: pattern_kind :type: str | None .. py:attribute:: name_class :type: str | None .. py:attribute:: datatype_library :type: str | None .. py:attribute:: datatype_name :type: str | None .. py:attribute:: datatype_parameters :type: tuple[tuple[str, str], ...] .. py:attribute:: synthetic :type: bool .. py:class:: RelaxNGSchemaDescription A deterministic grammar inventory. ``start_ids`` names the compiled start pattern component. Components are sorted by kind rank and then ID; ``dependencies`` is the compilation's canonical resource closure verbatim, including every dependency record whose content merges into one resource component. .. py:attribute:: start_ids :type: tuple[str, ...] .. py:attribute:: components :type: tuple[RelaxNGComponentDescription, ...] .. py:attribute:: dependencies :type: tuple[pyxsd.relaxng.resources.ResourceDependency, ...] .. py:function:: describe_component(schema, component_id) Return one exact component, raising :class:`KeyError` for any other ID. .. py:function:: describe_schema(schema) Return the immutable grammar inventory, valid schema or not. An invalid compilation still exposes its grammar, start pattern, definitions, patterns, and resource dependencies. Projection routes are omitted without asking an invalid schema for ``schema.projection``; the report and its verdict are never changed. .. py:function:: find_components(schema, *, text = None, kind = None, namespace = None) Filter by literal case-insensitive text, component kind, and namespace. ``None`` leaves a filter unrestricted; an empty namespace selects components without an expanded-name namespace. Text is matched literally over the ID, name, namespace, pattern kind, canonical name class, and datatype library/type; no caller expression is evaluated. .. py:function:: related_components(schema, component_id, *, direction, depth) Breadth-first component traversal, excluding the seed and duplicates. .. py:class:: RelaxNGLimits Optional budgets for pattern-graph, evidence, capture, and diagnostics. A pattern-node budget counts distinct semantic graph nodes. Derivative, memo-entry, evidence-state, evidence-edge, scalar-witness, and projection-route budgets bound their named work. An evidence binding summary is one retained ``(occurrence, scalar pattern)`` record in the schema-static table used for wrapper selection; it is not a proof node, edge, surviving witness, or capture record. ``max_capture_entries`` bounds the independent optional annotation table and truncates it visibly instead of raising. A ``max_diagnostics`` budget is a truncatable retention budget, not a work budget. ``max_compact_tokens`` charges emitted compact tokens cumulatively; ``max_compact_depth`` checks the parser's current nesting depth as a high-water observation rather than charging every production entry, and the compact reader caps that depth at a fixed interpreter-safety ceiling so a larger or unset budget cannot leak ``RecursionError``. The compiler's graph and semantic correctness checks run regardless of these values; a projection budget never skips a correctness check. .. py:attribute:: max_pattern_nodes :type: int | None :value: None .. py:attribute:: max_derivative_states :type: int | None :value: None .. py:attribute:: max_memo_entries :type: int | None :value: None .. py:attribute:: max_evidence_states :type: int | None :value: None .. py:attribute:: max_evidence_edges :type: int | None :value: None .. py:attribute:: max_scalar_witnesses :type: int | None :value: None .. py:attribute:: max_binding_summaries :type: int | None :value: None .. py:attribute:: max_capture_entries :type: int | None :value: None .. py:attribute:: max_projection_routes :type: int | None :value: None .. py:attribute:: max_diagnostics :type: int | None :value: None .. py:attribute:: max_compact_tokens :type: int | None :value: None .. py:attribute:: max_compact_depth :type: int | None :value: None .. py:class:: RelaxNGSchema An immutable compiled RELAX NG 1.0 schema. ``report`` holds the merged reader, simplification, composition, and correctness findings of this compilation. ``grammar`` is the composed semantic graph with every reference bound; its ``start`` may be a :class:`~pyxsd.relaxng.patterns.Ref` edge whose ``target`` is the root element pattern. ``dependencies`` is the complete canonical resource closure, and ``namespace_context`` is the root resource's namespace context, keeping the authored root frame exactly (an undeclared default namespace remains an empty entry). ``limits`` is the schema's effective budget declaration (unlimited when none was supplied), and ``datatype_fingerprint`` identifies the effective datatype registry. Separate schema objects are independent and may be compiled or used concurrently. One schema does not support reentrant instance parsing; parses of one schema must not run concurrently or reentrantly. .. py:attribute:: report :type: pyxsd.validation.ValidationReport .. py:attribute:: grammar :type: pyxsd.relaxng.simplify.CompiledGrammar .. py:attribute:: namespace_context :type: pyxsd.namespaces.NamespaceContext .. py:attribute:: limits :type: pyxsd.relaxng.limits.RelaxNGLimits .. py:attribute:: datatype_fingerprint :type: str .. py:method:: compile(source, *, syntax = 'auto', datatype_libraries = None, resource_policy = None, xml_policy = None, xml_limits = None, limits = None) :classmethod: Compile one RELAX NG 1.0 schema in XML or compact syntax. - ``source`` is a local path or a readable text/binary stream. Remote resources require an authorizing :class:`~pyxsd.resource_policy.ResourcePolicy`; an already-parsed ``Element`` is deliberately not accepted because it cannot carry policy parser evidence. - ``syntax`` selects the root frontend. ``"auto"`` (the default) selects compact only for a named root whose path component ends in ``.rnc``, case-insensitively; URL query and fragment components do not participate. Anonymous streams and every other named source stay XML. ``"xml"`` and ``"compact"`` are explicit overrides. Every include and external dependency inherits the root syntax regardless of its own suffix, so one closure never mixes the two frontends. - ``datatype_libraries`` maps library URIs to application registrations. It augments the built-in and XSD libraries and may replace a nonreserved library; reserved identities cannot change. - ``resource_policy`` is a trusted application policy whose ``read`` and ``parse`` own every resource read, including includes and external references. A compact resource uses only the policy's ``read`` admission; its XML ``parse`` is never called for compact bytes. ``xml_policy`` and ``xml_limits`` configure XML parsing only without a policy and cannot be combined with one; together with a compact root they are rejected before input is read. - ``limits`` bounds schema-side compiler work. ``None`` leaves every budget unlimited; exhaustion of a work budget raises :class:`~pyxsd.relaxng.errors.RelaxNGLimitError`. A configured ``max_diagnostics`` only bounds report retention, further tightening any policy report bound: beyond it, findings stay counted but are not retained, so ``suppressed_count`` exposes the incomplete report and ``diagnostics_complete`` is false. ``max_compact_tokens`` is cumulative across the root and every nested compact resource, and ``max_compact_depth`` is a high-water observation. Truncation never raises a limit error or removes an invalid verdict. Grammatical errors are recorded on :attr:`report` instead of raising. A malformed compact root raises :class:`~pyxsd.relaxng.errors.RelaxNGCompactSyntaxError`; a malformed nested compact resource is a schema finding at its exact location. Unreadable or malformed input and unsupported capabilities raise :class:`~pyxsd.exceptions.PyXSDError` or a more specific :class:`~pyxsd.exceptions.PyXSDError` subclass. .. py:property:: projection :type: pyxsd.relaxng.projection.ProjectionPlan The immutable schema-static route graph shared by typed adapters. Compilation materializes this plan after successful correctness checks. The cached property preserves the existing schema constructor signature; directly constructed schemas use the same checked entry condition. .. py:property:: projection_classes :type: pyxsd.relaxng.binding.ProjectionClassFactory The generated-class factory for this schema's finite route plan. One factory per compiled schema preserves class identity across repeated parses, capture settings, and recursive instance depths. Separate schemas own separate class objects even for equivalent plans. .. py:property:: dependencies :type: tuple[pyxsd.relaxng.resources.ResourceDependency, ...] The complete canonical resource closure of the compilation. .. py:method:: stub(*, compact = False, component_ids = None, depth = None) Return typing-stub text for this schema's runtime projection classes. The full form is an importable-quality ``.pyi`` document containing one class block per stable projection route, generic-route comments, and start aliases. ``compact=True`` selects the deterministic agent view: a two-line header with an alias legend, one line per class and member, and a trailing start line. ``component_ids`` selects RELAX NG introspection component IDs; ``depth`` bounds their outgoing ``uses`` dependencies (``None`` follows every reachable component). Only selected ``route`` components can become classes, so a definition or pattern ID is an inventory seed rather than a class. An empty selection emits no classes or aliases. Unknown IDs raise ``KeyError`` and negative depths raise ``ValueError``. Emitting never requires a valid schema report and never calls :meth:`require_valid`; a schema with compilation errors emits a deterministic explanatory comment and its projection plan is not consulted. Selection does not mutate the schema. .. py:method:: require_valid() Raise :class:`~pyxsd.exceptions.ValidationError` when compilation failed. .. py:method:: iter_parse(sources, *, errors = 'raise') Lazily parse explicit local sources with this compiled schema. This is the same sequential batch orchestration as :meth:`pyxsd.Schema.iter_parse`: the schema is checked before the first input is pulled, each input is parsed only when requested, expected I/O and malformed-XML failures are isolated in report mode and stop the batch with :class:`pyxsd.batch.BatchParseError` in raise mode, duplicate source IDs are rejected, and files are closed before an outcome is yielded. Documents are validation-only RELAX NG documents, so each item is parsed with ``typed=False``. Parsing one schema remains non-reentrant, but the guard covers each item parse rather than the yield boundary: a yielded document may revalidate while the batch stays open. .. py:method:: parse(xml, *, xml_policy = None, xml_limits = None, typed = True, capture = 'none', capture_xdm = False, limits = None) Parse one instance document into the generic RELAX NG tree. - ``xml`` accepts a path, a readable text/binary stream, or a pre-parsed ``Element`` at the caller-trusted boundary, matching :meth:`pyxsd.Schema.parse`. Malformed or unreadable input raises :class:`~pyxsd.exceptions.PyXSDError`; grammar mismatches return a document with instance findings. - ``xml_policy`` and ``xml_limits`` configure this instance parse only. A pre-parsed ``Element`` is a trusted value, so parser options do not apply to it. A schema compiled with a trusted :class:`~pyxsd.resource_policy.ResourcePolicy` reads and parses instances through that policy instead; combining the two is rejected before input is read. - ``typed`` defaults to ``True``. A valid typed document receives complete binding evidence and exposes ``scalar_value()`` and ``attribute_value()`` on the lexical tree; stable routes use their generated projection class, while a route with a semantic fallback and every descendant without a unique route stay generic. No instance value chooses a class layout. ``typed=False`` remains evidence-free validation-only parsing and rejects typed access explicitly. Typed parsing never changes the boolean verdict. - ``capture`` is ``"none"`` by default. ``"patterns"`` is accepted with ``typed=True`` as the setting for an optional, parse-scoped annotation table; ``capture="patterns", typed=False`` is rejected with ``ValueError`` before any input is read. Other values are rejected the same way. The independent ``max_capture_entries`` budget truncates only that table, visibly and without raising; capture settings never truncate mandatory scalar evidence. Table materialization is lazy: parsing succeeds whenever ``capture="none"`` does, and a declared datatype decoder failure surfaces only when ``document.annotations`` is requested. - ``capture_xdm`` retains the existing opt-in XDM meaning: the same source revision also becomes an unannotated XML-tree view. A pre-parsed ``Element`` is captured structurally, without source bytes or spans. Per-element bindings recorded in the schema's namespace context are used for both validation and capture. ``RelaxNGDocument.revalidate`` replays this request against its reparsed clone, including after a transformed-root wrapper dropped the stale capture object, so the fresh document captures its own current revision. - ``limits`` bounds this instance's derivative and evidence work. ``None`` uses the compiled schema's limits. Supplying a :class:`~pyxsd.relaxng.limits.RelaxNGLimits` replaces that declaration for this parse, and each ``None`` field in it means unlimited rather than inheriting the schema value; callers preserving selected schema defaults can pass ``dataclasses.replace(schema.limits, max_memo_entries=...)``. The schema value is never modified. Exhaustion raises :class:`~pyxsd.relaxng.errors.RelaxNGLimitError` instead of reporting invalidity. A configured ``max_diagnostics`` only bounds finding retention; suppressed findings stay counted, the report stays invalid, and ``diagnostics_complete`` becomes false. One schema must not parse concurrently or reentrantly. A parse sets a non-blocking guard before input is consumed and clears it on every exit path, including malformed input, limit exhaustion, and generator close. A competing parse raises ``RuntimeError`` immediately instead of waiting; separate schema objects remain independent. The schema report's errors are rejected before instance input is consumed. Every successful call returns a fresh document report: frozen schema-phase issue objects followed by this parse's instance findings. Instance findings cover every independent recovery case in source order; recovered states never make the document valid. .. py:method:: from_data(data, *, format = 'pyxsd-json', element = None, namespaces = None, fidelity = 'strict') Build and validate a document from JSON-compatible *data*. The data is converted to a deterministic Clark-named ElementTree with one recorded datatype context per constructed element, then parsed by the ordinary guarded instance path with ``typed=True``, default capture, and no XDM. Conversion problems (malformed shape, wrong containers, duplicate expanded names, bare null, malformed tags, or an ambiguous root) raise :class:`~pyxsd.exceptions.PyXSDError` before validation; lexically invalid content lands on the returned document's report exactly as for XML input. - ``format`` selects one of the five published data formats. - ``element`` optionally names the root with a local, Clark, or EQName spelling. Root-absorbed formats require it when the start pattern admits more than one name; otherwise it only narrows and confirms. - ``namespaces`` seeds the root's inherited prefix frame. In-band declarations and scalar-tag contexts shadow it per element. - ``fidelity`` selects strict loss rejection or the documented best-effort fallbacks. An unknown value raises ``ValueError``. .. py:method:: from_json(source, *, format = 'pyxsd-json', element = None, namespaces = None, fidelity = 'strict') Parse JSON text or UTF-8 bytes and bind it like :meth:`from_data`. *source* is JSON content, not a path. The format and fidelity names are validated before the JSON is parsed, and duplicate object keys and the non-standard ``NaN``/``Infinity`` constants are rejected through the shared JSON boundary. The remaining options and error behavior match :meth:`from_data`. .. py:method:: json_schema(*, format = 'pyxsd-json', element = None, fidelity = 'strict', typed = True, always_list = False) Describe this schema's JSON data contract as Draft 2020-12 JSON Schema. The generated schema matches what :meth:`from_data` accepts and :meth:`RelaxNGDocument.to_data` produces for the selected format, so every export from a valid, current revision validates against it. It is a structural description, never full RELAX NG validation: grammar validity, name classes, datatype contexts, candidate identity, and unexpressed ordering are listed under ``x-pyxsd-validation.unvalidated``. - ``format`` - the data-format contract; the RELAX NG profile describes ``"pyxsd-json"`` and advertises ``x-pyxsd-profile: "relaxng"``. - ``element`` - an optional local, Clark, or EQName spelling that narrows the start name class; ``None`` describes every admitted root name, keeping an open class symbolic. - ``fidelity`` - ``"strict"`` or ``"best-effort"`` representation handling; an unknown value raises ``ValueError``. - ``typed`` / ``always_list`` - native-only export options; they must keep their defaults for every other format. .. py:data:: compile .. py:class:: RelaxNGElement The lexical node used by RELAX NG documents and their projections. Typed scalar and attribute access requires a typed parse and returns ``None`` when no interpretation is available at that position. An invalid typed document raises :class:`~pyxsd.exceptions.ValidationError`; edits make the interpretation stale and raise :class:`~pyxsd.relaxng.errors.StaleInterpretationError` on typed access. .. py:method:: from_etree(element, *, namespaces = None, base_uri = None, source = None) :classmethod: Build a RELAX NG lexical tree, accepting authored origins as source links. .. py:method:: assign_fields(fields, *, selections = ()) Encode and apply one atomic transaction from a field mapping. This is the collision-safe entry point: every key is resolved as a generated projection alias or the route's scalar descriptor name, so an XML field named ``assign``, ``assign_fields``, or ``selections`` cannot shadow the transaction API. Every value is shape-checked, encoded from the plan's compile-time patterns, and context-checked before any lexical store changes. A successful write dirties the whole revision but never certifies document validity or refreshes typed evidence. .. py:method:: assign(*, selections = (), **fields) Convenience keyword form of :meth:`assign_fields`. Field aliases are reserved away from ``assign`` and ``assign_fields``; use :meth:`assign_fields` for a field whose alias is literally ``selections`` so the mapping key is not confused with this keyword. .. py:class:: AlternativeValue One immutable, non-preferential scalar interpretation snapshot. .. py:attribute:: lexical :type: str .. py:attribute:: candidates :type: tuple[Candidate, ...] .. py:attribute:: context :type: pyxsd.relaxng.datatypes.DatatypeContext .. py:attribute:: grammar_fingerprint :type: str .. py:attribute:: revision :type: int .. py:attribute:: interpretations :type: tuple[ListInterpretation, ...] :value: () .. py:attribute:: document_evidence :type: bool :value: False .. py:method:: as_type(selector) Decode the one surviving atomic datatype selected by *selector*. ``"xsd:name"`` means the RELAX NG XSD datatype-library URI, never an instance prefix binding; a tuple selects an explicit ``(library_uri, type_name)``. Several distinct matching contracts require :meth:`as_candidate`. .. py:method:: as_candidate(candidate_id) Decode the candidate with exactly *candidate_id*. .. py:method:: as_interpretation(candidate_id) Return the list interpretation attached to *candidate_id*. .. py:method:: as_python() Return the only decodable candidate's Python value, or fail explicitly. .. py:class:: ListInterpretation One whole-list contract with correlated token assignment evidence. ``token_candidates`` is a per-token marginal view, not a product: choosing one candidate at each position is only legal when the retained list derivation graph contains a complete assignment using them. ``as_types`` performs that whole-assignment check. ``as_python`` returns a value only when exactly one complete decodable interpretation survives; equal Python values from distinct contracts are never merged. ``shape`` is the schema-static typing classification. ``tuple`` and ``list`` are ordinary typed results when every token decodes; any other arrangement keeps this interpretation object so callers can inspect token alternatives instead of receiving an invented value. An empty permitted list is a valid interpretation with no token groups, never a failure. .. py:attribute:: lexical :type: str .. py:attribute:: token_spans :type: tuple[pyxsd.relaxng.validator.TokenSpan, ...] .. py:attribute:: token_candidates :type: tuple[tuple[Candidate, ...], ...] .. py:attribute:: context :type: pyxsd.relaxng.datatypes.DatatypeContext .. py:attribute:: grammar_fingerprint :type: str .. py:attribute:: revision :type: int .. py:attribute:: contract :type: pyxsd.relaxng.contracts.ScalarContract .. py:attribute:: candidate_id :type: str .. py:attribute:: shape :type: pyxsd.relaxng.contracts.ListShape .. py:attribute:: constraints :type: pyxsd.relaxng.evidence.TokenConstraintGraph .. py:property:: is_plain :type: bool Whether this is a statically plain, completely decodable list. .. py:method:: as_python() Return the only complete decodable interpretation, or fail explicitly. .. py:method:: as_types(selectors) Decode one datatype selector per token after a whole-assignment check. A selector names the atomic datatype expected at that token position. Per-token existence is insufficient: the selected contracts must occur together in a complete retained list derivation. The check reuses the compact constraint graph, so it never enumerates token assignments.