Commit Graph

122 Commits

Author SHA1 Message Date
b3bbacb4e8 feat(canonical): C14N 2.0 sequential prefix rewrite, QName-aware values, node-set selection (#85) 2026-06-09 04:06:02 +02:00
e77b39a449 feat(canonical): node-subset C14N with ancestor namespace and xml:* inheritance (#85) 2026-06-09 03:55:54 +02:00
87fd7ba889 feat(emitting): textEscaping round-trip option to preserve carriage returns (#91) 2026-06-09 03:48:20 +02:00
46131bff1b feat(model): first-class doctype/entity-reference/namespace nodes, ownerDocument, adoption (#90) 2026-06-09 03:43:24 +02:00
2db9915fb2 feat(schematron): support key(), document(), and current() in tests
Schematron tests, lets, and message expressions can now use key() backed
by xsl:key declarations parsed from the schema, document() loading an
external file through an injected documentLoader, and current() resolving
to the rule context node. A node-keyed function-table factory threads
through the evaluation. Completes the Schematron audit.
2026-06-09 03:30:43 +02:00
dbdf98e231 feat(relaxng): skip RNC >> follow-annotations, completing #79
A >> follow-annotation after a pattern (a foreign element name with
optional [ ... ] content) is skipped, chaining and combining with leading
annotations; neither carries schema semantics. Namespace declarations
inside annotations were already dropped by the annotation skipper, so the
RNC compact syntax is now fully covered.
2026-06-09 03:20:47 +02:00
7c24ada92b feat(xslt): document() fragments and base-URI resolution, completing #82
A document() reference with a #fragment selects a subset of the loaded
document via XPointer; a node-set first argument unions the documents
named by each node's string value; and a relative URI is resolved against
a caller-supplied baseURI (the loader is wrapped so xsl:include/xsl:import
resolve the same way). Closes the XSLT function/output audit.
2026-06-09 03:12:49 +02:00
4ea84b3d58 feat(xslt): make result-tree fragments usable as node-sets
An xsl:variable with a body now binds a queryable document fragment (its
instantiated result converted to a TreeNode document) instead of a plain
string, so count($rtf/*), $rtf/child, and for-each over $rtf/... work.
It still has its concatenated text as a string value, so existing string
uses are unchanged. Part of #82.
2026-06-09 03:04:56 +02:00
3fec78da51 feat(xslt): implement xsl:output cdata-section-elements
The text content of the named result elements is emitted in CDATA
sections rather than escaped: the result tree's text children of those
elements are converted to CDATA nodes before serialization, leaving
nested and other elements unaffected. Part of #82.
2026-06-09 02:58:34 +02:00
2a40300479 feat(xslt): emit xsl:output doctype-public/doctype-system
When doctype-system (optionally with doctype-public) is set on xsl:output,
a <!DOCTYPE> for the result's root element is emitted before the
serialized output: PUBLIC when both identifiers are given, SYSTEM
otherwise. Works for the XML and HTML output methods. Part of #82.
2026-06-09 02:53:50 +02:00
47b88f19b2 feat(xslt): key() over a node-set second argument
key(name, node-set), including key('k', .), now unions the indexed nodes
for every value node's string value and de-duplicates, instead of using
only the first node's string value. A string value still works directly.
Part of #82.
2026-06-09 02:50:24 +02:00
41a48d3130 feat(xslt): serialize method=html output by the HTML rules
An xsl:output method=html result is serialized through PureXML.HTML
(void elements emitted without a self-closing slash, raw-text elements
like script/style left unescaped) instead of as XML. Part of #82.
2026-06-09 02:48:00 +02:00
e30672d72b feat(xslt): implement xsl:sort case-order
case-order=upper-first/lower-first makes the string comparison
case-insensitive, with case used only to break ties among otherwise-equal
strings; without it the default codepoint order is unchanged. Part of #82.
2026-06-09 02:37:43 +02:00
322fd013e9 feat(xslt): add generate-id, system-property, *-available functions
generate-id returns a stable per-node identifier (the context node when
no argument is given, the empty string for an empty node-set);
system-property reports the XSLT version and vendor; element-available and
function-available answer against the implemented instruction and function
sets; unparsed-entity-uri is a stub. Part of #82.
2026-06-09 02:20:36 +02:00
610b7d0ca0 feat(xslt): implement xsl:namespace-alias, completing #81
A literal result element and its attributes in a stylesheet namespace
bound by stylesheet-prefix are rewritten on output to the namespace and
prefix bound by result-prefix (#default supported), so a stylesheet can
emit literal xsl: elements. Prefixes resolve through the in-scope xmlns
declarations; aliases fold across include/import. Splits AVT parsing into
XSLTAVT.swift and trims the transformer to stay within length budgets.
2026-06-09 02:10:16 +02:00
2d2572e265 feat(xslt): implement xsl:decimal-format for format-number
format-number now honors named and default decimal formats: the decimal
separator, grouping separator, percent, minus sign, zero-digit (for
non-Latin digit sets), NaN, and infinity symbols come from the chosen
xsl:decimal-format, in both the picture and the output. FormatNumber is
parameterized over the symbol set and the formats thread through the
function table; folded across include/import.
2026-06-09 01:59:37 +02:00
61ab8ce8f9 feat(xslt): implement xsl:fallback for forwards-compatible processing
An unrecognized XSLT element instantiates its xsl:fallback children in its
place, or is dropped when it has none; a fallback under a supported
instruction is ignored. The fallback content is handled in the instantiate
loop alongside variables, so the evaluate dispatch stays within budget.
2026-06-09 01:52:21 +02:00
4f11bafa28 feat(xslt): implement xsl:apply-imports
Re-applies templates to the current node in the current mode, considering
only templates of lower import precedence than the one being instantiated,
falling back to the built-in rule when none match. Threads the current
mode and import precedence through the evaluation context, and moves the
transformer runtime types into XSLTRuntime.swift (namespaced, via private
aliases) to stay within the file-length and namespacing gates.
2026-06-09 01:49:33 +02:00
21ed15b1ec refactor(xslt): keep ResultItem/XSLTContext file-private for namespacing
Only the static deduplicated helper moves to XSLTElements.swift (it needs
no private types); attributeSetAttributes stays in the transformer so the
evaluation context and result-item types remain file-private, satisfying
the one-file-scope-type namespacing gate.
2026-06-09 01:41:48 +02:00
22cd88f8ba feat(xslt): implement xsl:attribute-set and use-attribute-sets
Named attribute sets apply to a literal result element or xsl:element via
use-attribute-sets; sets may include other sets recursively with a cycle
guard, set attributes are lowest precedence so the element's own
attributes override them, and same-named attributes collapse to the last.
Folded across xsl:include/xsl:import. Splits the element-building helpers
into XSLTElements.swift to stay within the file-length budget.
2026-06-09 01:39:45 +02:00
367b5b9425 feat(xslt): implement xsl:message with terminate
xsl:message instantiates its body as diagnostic text and produces no
result-tree output; terminate=yes records the text and aborts the
transform with an XSLTError.terminated, halting further instantiation.
Splits the transform entry points into XSLTTransform.swift and moves the
message case to keep within the complexity and file-length budgets.
2026-06-09 01:29:37 +02:00
10d9525e3e feat(xslt): implement xsl:strip-space and xsl:preserve-space
Whitespace-only text nodes are removed from the source tree for elements
named by strip-space before transformation, with preserve-space and a
more specific name test winning over *, and xml:space=preserve on a
source element or ancestor overriding the stripping. The name sets fold
across xsl:include/xsl:import. Refactors the stylesheet compile loop
through a Parts accumulator to absorb the new top-level elements within
the complexity budget.
2026-06-09 01:22:59 +02:00
d80718c530 feat(relaxng): distinguish undeclared attribute from invalid value
A RELAX NG attribute failure now reports an undeclared attribute
("attribute @b is not allowed on <n>") separately from a declared
attribute carrying a bad value ("attribute @count on <n>: 'abc' is not a
valid integer"), quoting the value and naming its datatype by reusing the
text detail. The declared value pattern is found by matching the
attribute name through the residual.
2026-06-09 01:11:54 +02:00
3be6832c23 feat(relaxng): quote the offending value and name the datatype in text errors
A RELAX NG text/datatype mismatch now reports the rich datatype reason
(quoting the value and naming the type, e.g. 'abc' is not a valid
integer) and a value mismatch quotes both the actual text and the
required literal, instead of a generic "text content is not valid". The
detail is peeled from the content pattern at the failure point through
choice, group, list, and ref.
2026-06-09 01:09:29 +02:00
fb31033ce8 feat(dtd): located content-model errors with recovery hints
An element whose children break its content model now names each stray
child outside the model's alphabet individually, and reports a pure
order/count violation once with the allowed elements as a hint, instead
of a single opaque "do not match its content model". Adds an alphabet
extractor to the content-model matcher. This brings DTD to the same
located standard as the XSD, RELAX NG, and Schematron validators, so all
four schema languages give editor-grade diagnostics.
2026-06-09 00:59:25 +02:00
ea5387db90 feat(xsd): located, recovering content-model errors
A content-model violation is now placed at the offending child with a
recovery hint naming what was expected, instead of one opaque "content
does not match the content model" per element. The sequence/choice
automaton is walked child by child via its follow-set to flag the first
child the model rejects, or the incomplete content at the end; an xs:all
group recovers past each stray child and reports every missing required
member. Well-placed children are still validated for their own content,
so an editor sees every problem at once. Brings XSD to the same located,
recovering standard as the RELAX NG, DTD, and Schematron validators.
2026-06-09 00:55:17 +02:00
ae271d65f6 feat(relaxng): located, recovering validation errors for editor use
Adds RelaxNG.errors(in:) reporting every way a document fails the schema
as individual located errors with coding paths, recovering past each
failure so all of a faulty document's problems surface at once instead of
only the first. Errors carry recovery hints naming the element types
accepted at the failure point, and distinguish unexpected elements,
invalid or missing attributes, invalid text/datatype content, and missing
required content. RelaxNG.validation() exposes the schema as a
Validation<Node, Void>, composing with the same framework as the XSD,
DTD, and Schematron rules. The boolean derivative engine remains the
authority on validity; the diagnostic walk only places and explains the
failures, recovering each step so it never cascades. Splits the engine
and the diagnostics into separate files.
2026-06-09 00:40:56 +02:00
2414dbc3bc feat(catalog): honor group-level prefer override
A prefer attribute on a <group> (or nested <catalog>) overrides the
catalog-wide preference for the <public> entries within it, inherited
through nested groups. The resolver records each public entry's effective
preference and consults it when falling back from an unmatched system
identifier, so two entries in one catalog can prefer differently. A system
match still always wins.
2026-06-08 18:05:03 +02:00
d7a40b9a7a feat(schematron): instantiate abstract patterns with is-a/param
A <pattern abstract="true"> is a template whose rule queries carry $name
references; a <pattern is-a="…"> with <param> children instantiates it,
substituting each parameter into the template's context, test, <let>
value, and <value-of select=> before the XPath is compiled. The
substitution is a single left-to-right pass, so a substituted value is
never rescanned and a short name never captures a longer one; $name
references that are not parameters stay as written. The template itself
contributes no rules.
2026-06-08 17:58:33 +02:00
9845e1cd9d feat(relaxng): fold RNC ~ string concatenation
A string literal split with ~ ("a" ~ "b") is the single literal "ab",
the way long values and namespace URIs are wrapped across lines. The fold
applies wherever a string literal is read: value literals and the URIs of
namespace/datatypes/include/external declarations.
2026-06-08 17:38:58 +02:00
79f424321c feat(relaxng): compare typed <value> in the datatype value space
A <value> pattern now carries its datatype, so matching compares the
instance and the literal in that type's value space rather than purely
lexically. Numeric and date/time types compare by value (1 equals 01,
1.5 equals 1.50); booleans treat 1/true and 0/false as equal; string and
token compare by their whitespace-normalized lexical form, as before.
Untyped values default to the built-in token type, and a bare string
literal in the compact syntax is token-typed. Durations and binary types
fall under the lexical rule.
2026-06-08 17:36:16 +02:00
147d776d21 feat(relaxng): resolve datatypeLibrary and nsName subtraction
Adds a datatypeLibrary-aware datatype resolver to the XML-syntax parser:
the in-scope library is inherited from the nearest ancestor, the default
(empty) library defines only string and token, and the W3C XML Schema
library defines the full built-in set. A type the in-scope library does
not define is an unknown datatype, so the <data>/<value> pattern matches
nothing rather than silently validating.

Adds an nsNameExcept name-class case so nsName with an <except> child
(XML syntax) and prefix:* - name subtraction (compact syntax) narrow a
namespace wildcard. The compact lexer splits prefix:* into a trailing-
colon word plus a star symbol, which the parser now recognizes.

Existing RELAX NG facet tests declared XSD types without the library and
relied on lenient resolution; they now declare the XSD datatypeLibrary,
matching what a conformant processor requires.
2026-06-08 17:21:49 +02:00
e24004dd2a feat(relaxng): handle RNC annotations and div grouping
The compact-syntax parser now skips [ ... ] documentation/grammar
annotations (balanced over nesting) wherever they may appear, before a
define or before a pattern, and treats div { ... } as transparent
grammar grouping that contributes its defines and start directly. A
define literally named div still parses when assigned. Splits the
name-class and token helpers into a companion file to stay within the
type and file length budget.
2026-06-08 17:12:35 +02:00
3a1ecb503a feat(catalog): SGML Open (TR 9401) catalog format
Resolver(sgml:) parses the legacy SGML catalog format: PUBLIC, SYSTEM,
DELEGATE, CATALOG, BASE, and OVERRIDE entries with -- comment --
delimiters. Replacement URIs resolve against BASE and the supplied
baseURI; OVERRIDE YES/NO maps to the prefer-public fallback. Unknown
keywords are skipped tolerantly. Feeds the same Resolver as the XML
catalog.

Part of #86
2026-06-08 17:03:06 +02:00
3887b33e4e feat(relaxng): compact name-class subtraction (* - name)
The compact-syntax name class * - nameClass now parses as anyName except
the subtracted class (the model already had anyNameExcept). ns:* - name
would need an nsName-except model case and is left as a refinement.

Part of #79
2026-06-08 16:58:24 +02:00
8438d94b44 feat(relaxng): compact-syntax datatype parameter blocks
The RNC datatype parameter block xsd:int { minInclusive = "5" } is now
parsed into facets (previously skipped), matching the XML-syntax <param>
support. The facet mapping is shared by both parsers through a new
RelaxNGFacets helper.

Part of #79
2026-06-08 16:55:57 +02:00
b3d535c77e feat(schematron): schema- and pattern-level let
<let> may now appear at schema and pattern level, not just in a rule.
Schema lets are evaluated once at the document root; pattern lets extend
them (also at the root); rule lets extend those at each context node. A
narrower-scope binding overrides a wider one of the same name.

Part of #80
2026-06-08 16:52:16 +02:00
28cbed0a70 feat(relaxng): <param> facets under <data>
A <data type=> pattern now carries a SimpleType (base + facets) rather
than a bare built-in, and its <param name=>value</param> children
populate the facets (minLength, maxLength, length, pattern, min/max
inclusive/exclusive, total/fraction digits), reusing the XSD datatype
facet validation. So a constrained datatype like xsd:string with
minLength rejects too-short values.

datatypeLibrary resolution, typed <value> comparison, and the RNC
datatype parameter blocks remain.

Part of #79
2026-06-08 16:48:24 +02:00
50a6afb3fc docs(validation): document the XSD validator scope decision; isolation-test each category
The validation framework already conforms to the OpenAPIKit idiom: named
composable Validation values, a Validator with blank/validating/
withoutValidating, located errors, parameterized over both subject and
document. The DTD layer is already four named rules.

XSD content validation stays a single recursive Validation
(contentValidity) rather than a rule per constraint, because XSD is a
recursive type system: a child's type is resolved from its parent's
content model and position, then rewritten by xsi:type and the derivation
controls mid-walk, so the constraint categories are interdependent and
cannot be split into independent rules without changing semantics or
duplicating the recursion. That is the sanctioned multi-error form.

To keep each category verifiable on its own (the idiom's testability),
add XSDCategoryTests exercising ComplexValidator directly per category
(attributes, content, nillable, fixed); derivation, wildcards, and
namespaces are already isolation-tested through crafted schema strings.

Closes #101
2026-06-08 16:41:50 +02:00
e2ba6a7359 feat(emitting): cdataAsText and asciiOnly save options
- cdataAsText emits a CDATA section's content as escaped text instead of
  a <![CDATA[ ... ]]> section.
- asciiOnly escapes every non-ASCII character as a numeric character
  reference, so the output is pure ASCII (libxml2's character-reference
  encoding).

Both apply to the Serializer and the incremental Writer through the
shared Escaping rules.

Closes #91
2026-06-08 16:34:57 +02:00
a76e9b3da3 feat(schematron): diagnostics
An assert/report may reference <diagnostic> messages by id through its
diagnostics= attribute; each referenced diagnostic is rendered (with the
same value-of/name/let substitution) and appended to the finding for
extra per-failure detail. <diagnostics> is collected schema-wide.

Schema/pattern-level let, abstract patterns, and key()/document() remain.

Part of #80
2026-06-08 16:30:13 +02:00
7e04f6056c feat(schematron): abstract rules and extends
A <rule abstract="true" id="x"> is a template that does not fire on its
own; a concrete rule pulls in its let bindings and assertions with
<extends rule="x"/>, prepended so the concrete rule extends rather than
replaces them.

Part of #80
2026-06-08 16:26:30 +02:00
d0671e40ba feat(schematron): rule-level let variable bindings
<rule> may now declare <let name= value=> bindings, evaluated at each
context node in order (so a later binding can reference an earlier one
through $name). The bindings are available to the rule's assert/report
tests and to <value-of select="$name"> in messages, using the XPath
engine's existing variable support.

Schema- and pattern-level let, abstract rules/extends, diagnostics, and
key()/document() remain.

Part of #80
2026-06-08 16:23:26 +02:00
502aa26438 feat(catalog): xml:base and RFC 3986 relative-URI resolution of entry URIs
Catalog replacement URIs (uri, rewritePrefix, delegate/next catalog) are
now resolved against the catalog's base URI and any in-scope xml:base,
reusing the existing RFC 3986 URIReference resolver. Resolver(_:baseURI:)
supplies the catalog's own location; xml:base on the catalog/group/entry
elements scopes nested entries. An empty base leaves relative URIs as
written, so catalogs without a base behave exactly as before.

The legacy SGML catalog format and group-level prefer override remain.

Part of #86
2026-06-08 16:19:45 +02:00
24a862e3a0 feat(relaxng): combine on define (choice/interleave merging)
A define repeated with combine="choice" or combine="interleave" now
merges with the existing definition (as a choice or interleave pattern)
instead of the last one silently replacing it. A plain redefinition with
no combine still replaces. Applied consistently in a grammar and across
include merges.

<param> facets under <data>, datatypeLibrary resolution, typed <value>
comparison, and the RNC-syntax gaps remain.

Part of #79
2026-06-08 16:03:39 +02:00
2a77b56d2f feat(xpath): eval-time namespace context and XPointer xmlns()/xpath1() schemes
- Eval-time prefix bindings: Query.evaluate(over:namespaces:) and
  value(at:...:namespaces:) supply prefix to URI bindings, so a name test
  like q:item resolves q to a URI and matches by namespace regardless of
  the document's own prefix. The match is namespace-aware only when
  bindings are present, so existing unprefixed/prefix-string queries are
  unchanged.
- XPointer schemes: xpath1() evaluates an XPath expression (like
  xpointer()), and xmlns(p=uri) binds a prefix for the expression parts
  that follow it, threaded into the XPath evaluation.

The range() scheme (and so XInclude range inclusion) remains.

Part of #88
2026-06-08 16:00:15 +02:00
b13cdca739 feat(xinclude): content-negotiation hints, cycle detection, text+fragment
Three XInclude gaps from the audit:

- accept / accept-language / encoding are surfaced to the loader via a new
  XIncludeRequest and a process(_:base:loading:) overload, so a loader can
  honor content negotiation. The existing loadingURI form is kept.
- Cycle detection tracks the visited (resolved-URI) set along the current
  inclusion chain and raises XIncludeError.cycle, instead of relying only
  on the depth backstop; a non-cyclic diamond include is not flagged.
- parse="text" combined with an xpointer is rejected
  (XIncludeError.textWithFragment), since a fragment cannot select within
  unparsed text.

xpointer range() inclusion still depends on the XPointer range() scheme
(tracked in the XPointer issue).

Part of #87
2026-06-08 15:52:18 +02:00
68122ad887 feat(schematron): dynamic message content and phase support
Two ISO Schematron gaps, the most validator-relevant first:

- Dynamic messages: an assert/report message is now a template, so
  <value-of select=> renders the string value of its XPath at the context
  node and <name> renders the node's name. A finding can report actual
  values ("Age 120 must be under 100") instead of static text.
- Phases: <phase id><active pattern=> scopes which patterns run.
  validate(_:phase:) honors a requested phase or the schema's
  defaultPhase; nil or #ALL runs every pattern.

let variables, abstract rules/extends, diagnostics, and key()/document()
remain (the last depends on XSLT-style function injection).

Part of #80
2026-06-08 15:45:27 +02:00
b7da5652f3 feat(catalog): systemSuffix/uriSuffix entries and the prefer attribute
Two OASIS catalog gaps from the audit:

- systemSuffix and uriSuffix entries: an identifier ending in the rule's
  suffix maps to its URI, longest suffix winning, tried after exact and
  rewrite matches.
- prefer=public|system on the catalog: a system match always wins, and
  the public identifier is consulted as a fallback only when prefer is
  public or no system identifier was given (the OASIS rule). The default
  stays prefer=public.

xml:base / RFC 3986 relative-URI resolution of entry URIs and the legacy
SGML catalog format remain.

Part of #86
2026-06-08 15:31:10 +02:00
cd2f30a262 feat(emitting): attribute quote style, line endings, xml:space, writer namespaces
Broaden the serializer and writer options from the audit:

- attributeQuote selects single or double quotes; the active quote is
  escaped in values (apostrophe as &apos; in single-quote mode).
- lineEnding controls the inserted newline (set to CRLF for \r\n output).
- xml:space=preserve suppresses pretty-print indentation for an element
  and its subtree; xml:space=default re-enables it.
- Writer gains writeStartElementNS(prefix:localName:namespaceURI:) and
  writeNamespace(prefix:uri:), so callers no longer hand-format prefixes
  and xmlns attributes.

CDATA-vs-escape and entity re-escaping strategies are left as a
follow-up; the current escaping is the safe default.

Closes #91
2026-06-08 15:24:49 +02:00