* fix(xslt): keep namespace nodes on an included literal result element
An xsl:include'd stylesheet's declarations are absorbed after collectUnit
returns, and each literal result element resolves its 7.1.1 namespace nodes
by walking the weak parent chain back to its own included stylesheet element.
Those elements lived only in the write-only retainedRoots array, so an
optimized build released them before the deferred resolution ran and the
in-scope xmlns declarations vanished, dropping the namespace nodes the
included element should carry. The output was correct in debug and wrong in
release. Pin the retained roots across the resolution with
withExtendedLifetime. Imports were unaffected because they compile eagerly
while their tree is still a live local.
Catches Apache Xalan conformance case lre/lre05, surfaced by running the
apache/xalan-test corpus.
* fix(xslt): select a called template by import precedence, not document order
xsl:call-template looked up the target with the first match by position in the
flattened template list. Imports fold in before the including unit's own and
included templates, so when an import and an include both define a template
with the same name, the imported one was wrongly chosen. An included template
carries the including unit's higher import precedence and must win (XSLT 1.0
section 6). The lookup now picks the highest-precedence definition among the
same-name templates.
Closes Apache Xalan conformance cases namedtemplate17, namedtemplate18,
namedtemplate19, and namespace13 (removed from the xalan-test baseline). Full
suite 1608 tests green in debug and release; the Xalan suite passes.
* fix(xpath): string-value of a comment or PI node is its own data
The XPath string-value of a comment node is its character data and of a
processing-instruction node is its data (XPath 1.0 5.6, 5.7), but TreeNode
returned the empty string for both, so value-of select="comment()", and any
matching, sorting, or comparison over comment/PI nodes, produced nothing.
stringValue was conflated with the text-only concatenation that forms an
element's or root's string-value, where comment and PI descendants correctly
contribute nothing (5.1, 5.5). That concatenation now uses a separate
textContent, so an element's string-value still excludes comment and PI text
while a comment or PI node reports its own data.
Closes 24 Apache Xalan conformance cases across node, axes, position, select,
modes, conflictres, and variable (removed from the baseline). Full suite 1609
tests green in debug and release; the Xalan suite passes.
* fix(xslt): resolve top-level variables in any order, not document order
Top-level variables and parameters may reference one another regardless of
declaration order (XSLT 1.0 section 11.4), but they were evaluated once
top-to-bottom, so a forward reference (a global declared before the one it
uses) saw an undefined value and resolved to empty. Globals now evaluate to a
fixpoint: each pass re-evaluates the unsettled ones with the latest bindings,
so a dependency chain in any order settles in at most N passes, a pass that
changes nothing stops early, and a circular reference stops at the cap.
Extracted the evaluation into Transformer.evaluatedGlobals (XSLTGlobals.swift).
Closes Apache Xalan conformance cases variable33, variable34, variable35. Full
suite 1611 tests green in debug and release; the Xalan suite passes.
* fix(xslt): an empty-content variable with no select is the empty string
XSLT 1.0 section 11.2 makes <xsl:variable name="x"/> (empty content, no select)
equivalent to select="", so boolean() of it is false. It was always built as a
result-tree-fragment document node, which boolean() reports as true. A variable
with no select and empty content now yields the empty string; only non-empty
content remains a result tree fragment.
Closes Apache Xalan conformance cases boolean43 and boolean87. Full suite 1612
tests green in debug and release; the Xalan suite passes.
* fix(xpath): allow whitespace around the :: axis separator
XPath 1.0 allows whitespace between tokens, so `child :: sub` is the child axis
with node test `sub`. The parser only matched `::` immediately after the axis
name, so a spaced separator fell back to the child axis with the axis name read
as an element test, selecting nothing. parseAxis now skips whitespace after the
axis name and after `::`; on no match the reset to before the name is unchanged,
so a bare name step is unaffected.
Closes Apache Xalan conformance cases select16, select27, select28. Full suite
1613 tests green in debug and release; the Xalan suite passes.
* feat(xslt): document('') returns the stylesheet's own document
XSLT 1.0 section 12.1 makes an empty URI reference the document containing the
expression, so a stylesheet can read its own xsl:* nodes (embedded lookup
tables, self-inspection). The reference went straight to the document loader,
which has no entry for it, so document('') returned an empty node-set. The
transformer now keeps its parsed stylesheet tree and the document function
returns it for an empty reference, cached like any loaded document; a #fragment
still applies.
Closes Apache Xalan conformance cases select67, select68, idkey50, mdocs17,
namespace20. Full suite 1614 tests green in debug and release; Xalan passes.
* fix(xslt): implement unparsed-entity-uri from the source DTD
unparsed-entity-uri was a stub returning the empty string. It now reads the
source document type's unparsed (NDATA) entities, threaded to the function table
alongside the document loader, and returns the named entity's system URI; an
unknown name still returns empty.
Closes Apache Xalan conformance case expression02. Full suite 1615 tests green
in debug and release; the Xalan suite passes.
* fix(xpath): substring-after(s, '') returns s
Per the XPath 1.0 errata, an empty second argument matches at the start of the
string, so substring-after returns the whole string. The function bailed to the
empty string on an empty separator. substring-before(s, '') stays empty, as the
spec requires.
Closes Apache Xalan conformance case string143. Full suite 1615 tests green in
debug and release; the Xalan suite passes.
* fix(xslt): match a template mode by expanded name, not its prefix
XSLT 1.0 section 5.7 compares a mode by expanded name, so two prefixes bound to
the same namespace name the same mode. The prefixed QName string was stored and
compared verbatim, so apply-templates mode="foo:m" missed a template with
mode="moo:m" even when foo and moo share a namespace. Mode names on xsl:template
and xsl:apply-templates now resolve to {uri}local at parse time.
Moved the parser's declaration helpers to XSLTParserDeclarations.swift to keep
the file within the length budget.
Closes Apache Xalan conformance case modes16. Full suite 1616 tests green in
debug and release; the Xalan suite passes.
* fix(xslt): name a variable by expanded QName, not its prefix
XSLT 1.0 section 11.1 names a variable by expanded name, so two prefixes bound
to the same namespace name the same variable. The declared name and the
$prefix:local reference were compared as raw strings, so $new:x did not see a
variable declared txt:x even when new and txt share a namespace. A prefixed
declared name now resolves to {uri}local at parse time, and the XPath evaluator
falls back to the namespace-resolved name when the raw key is unbound, so a
caller-supplied raw binding still works and unprefixed names are unchanged.
Closes Apache Xalan conformance case variable55. Full suite 1617 tests green in
debug and release; the Xalan suite passes.
* fix(xslt): a match pattern predicate sees the global variables
XSLT 1.0 section 5.2 evaluates a pattern predicate with the top-level (global)
variables in scope, but pattern matching ran with no variables bound, so a
template like match="foo[. > $screen]" never matched ($screen was undefined).
The transformer supplies the global bindings to the match cache; they are
constant per transform, so they do not enter the cache key.
Closes Apache Xalan conformance cases match14 and idkey43. Full suite 1618 tests
green in debug and release; the Xalan suite passes.
* fix(emit): make a comment ending in a hyphen or containing -- well-formed
XML forbids `--` inside a comment and a `-` immediately before `-->`, so a
comment whose text ends with `-` was emitted as <!--text---> (malformed). The
serializer now inserts a space after each offending hyphen (the XSLT 1.0 16
recovery), so `text-` becomes `text- `. Applied in both the Serializer and the
streaming Writer via a shared Escaping.comment helper.
Closes Apache Xalan conformance cases output89 and output90. Full suite 1619
tests green in debug and release; the Xalan suite passes.
* fix(xslt): preserve whitespace adjacent to a CDATA section in a template
Text and CDATA are one text node in the data model, so <out> <![CDATA[test]]>
</out> is the node " test ", whose surrounding spaces must survive whitespace
stripping (XSLT 1.0 3.4). The template body dropped each whitespace-only text
node independently, so the spaces around the CDATA vanished. Adjacent text and
CDATA children now coalesce into one run, dropped only when the whole run is
whitespace; a purely whitespace run between elements is still removed.
Closes Apache Xalan conformance case whitespace13. Full suite 1620 tests green
in debug and release; the Xalan suite passes.
* fix(xslt): xsl:processing-instruction/comment keep only text-node content
XSLT 1.0 sections 7.4 and 7.6 make it an error for xsl:comment or
xsl:processing-instruction content to create a non-text node; the recovery is
to ignore the offending node together with its content. PureXML took the
string-value of all instantiated content, so a copied element leaked its text
into the PI or comment. The content now contributes only its text and CDATA
node items.
Closes Apache Xalan conformance case copy60. Full suite 1621 tests green in
debug and release; the Xalan suite passes.
* fix(xslt): xsl:attribute keeps only text-node content (errata E27)
XSLT 1.0 errata E27 makes it an error for xsl:attribute content to create a
non-text node, recovering by ignoring the offending node together with its
content (the same rule as xsl:comment/processing-instruction). PureXML took the
string-value of all instantiated content, so a copied element leaked its text
into the attribute value. The content now contributes only its text and CDATA
node items, reusing textNodesOnly.
Closes Apache Xalan conformance cases copy56 and copy58. Full suite 1622 tests
green in debug and release; the Xalan suite passes.
* fix(xslt): xsl:copy-of carries an element's inherited namespace nodes
XSLT 1.0 11.3 copies a node together with its namespace nodes, so copying an
element must reproduce its full in-scope set, including a declaration inherited
from an ancestor. copy-of reproduced only the element's own xmlns attributes,
dropping inherited ones. The inherited declarations are now added to the copied
element and the serializer's namespace fixup drops any already in the result
scope.
Closes Apache Xalan conformance cases copy09, copy27, copy48, mdocs09. Full
suite 1623 tests green in debug and release; the Xalan suite passes.
* fix(xslt): xsl:element with an unusable name passes its content through
XSLT 1.0 7.1.2 makes a name that is not a QName an error; the recovery (the
pinned element-name-not-QName "pass-through") emits the element's content
without the wrapper. The check rejected only an empty or multi-colon name, so
an undeclared prefix (none:foo) or a name that is not an NCName (this is a
string) still produced a malformed element. The name is now also rejected when
a part is not an NCName or its prefix is unbound.
Closes Apache Xalan conformance cases namespace40, namespace42, namespace43,
namespace60, namespace73, namespace79. Full suite 1624 tests green in debug and
release; the Xalan suite passes.
* fix(xslt): xsl:copy of the root node honors use-attribute-sets
Copying the root node produces no element of its own, so the use-attribute-sets
attributes have nowhere to attach on the copy and instead join the enclosing
result element (XSLT 1.0 7.5). copyInstruction dropped them for the root case;
they are now emitted ahead of the copied content so the enclosing element picks
them up.
Closes Apache Xalan conformance cases attribset27 and attribset29. Full suite
1625 tests green in debug and release; the Xalan suite passes.
* refactor(xslt): address review (canonical name/whitespace checks, html comment safety)
Review follow-ups on the conformance series:
- xsl:element name validation now uses the canonical Parsing.XMLCharacter
.isValidName instead of a hand-rolled grapheme check, which had narrowed valid
XML names (it dropped a name using a non-ASCII NameChar such as U+00B7).
- The template-body whitespace check reuses Parsing.XMLCharacter.isWhitespace
instead of a third local copy of the same predicate.
- The HTML serializer applies the section-16 comment recovery too, so a
method="html" comment ending in a hyphen (or containing two) is well-formed;
the C14N canonicalizer keeps comments verbatim as its contract requires.
Adds regression tests for a non-ASCII NameChar element name and for html
comment hyphen-safety. Full suite 1626 tests green in debug and release; the
Xalan suite passes.
355 lines
17 KiB
Swift
355 lines
17 KiB
Swift
typealias XSLTTree = PureXML.Model.TreeNode
|
|
|
|
// The accumulating declarations of a stylesheet as its top-level elements are
|
|
// compiled, plus the folding of an included or imported sub-stylesheet. File
|
|
// scope and private.
|
|
|
|
/// XSLTTree helpers for the XSLT parser. File-scope and private.
|
|
enum XSLTNode {
|
|
static let namespace = "http://www.w3.org/1999/XSL/Transform"
|
|
|
|
static func localName(_ node: XSLTTree) -> String? {
|
|
node.name?.localName
|
|
}
|
|
|
|
static func isXSL(_ node: XSLTTree) -> Bool {
|
|
node.kind == .element && (node.name?.namespaceURI == namespace || node.name?.prefix == "xsl")
|
|
}
|
|
|
|
static func attribute(_ node: XSLTTree, _ name: String) -> String? {
|
|
node.attributes.first { $0.name.localName == name }?.value
|
|
}
|
|
|
|
static func elementChildren(_ node: XSLTTree) -> [XSLTTree] {
|
|
node.children.filter { $0.kind == .element }
|
|
}
|
|
|
|
static func children(_ node: XSLTTree, named name: String) -> [XSLTTree] {
|
|
elementChildren(node).filter { localName($0) == name }
|
|
}
|
|
}
|
|
|
|
public extension PureXML.XSLT {
|
|
/// Errors compiling or running a stylesheet.
|
|
enum XSLTError: Swift.Error, Equatable, Sendable, CustomStringConvertible {
|
|
case notAStylesheet
|
|
/// An `xsl:message terminate="yes"` ended the transformation with this text.
|
|
case terminated(String)
|
|
|
|
public var description: String {
|
|
switch self {
|
|
case .notAStylesheet: "the document is not an xsl:stylesheet"
|
|
case let .terminated(message): "transformation terminated: \(message)"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension PureXML.XSLT {
|
|
/// Parses an XSLT 1.0 stylesheet document into a ``Stylesheet``: its template
|
|
/// rules (with computed default priorities) and global variables. The XSLT
|
|
/// vocabulary is recognized by namespace or the `xsl` prefix; other elements
|
|
/// are literal result elements.
|
|
enum XSLTParser {
|
|
/// Compiles one stylesheet unit, folding in `xsl:include`/`xsl:import`.
|
|
/// Import precedences are assigned post-order over the import tree (each
|
|
/// import lower than its importer, later siblings higher); a unit's
|
|
/// templates carry the [low, precedence) range apply-imports searches. An
|
|
/// included stylesheet joins the including unit at its precedence.
|
|
static func compile(_ top: XSLTTree, loader: (String) -> String?, counter: inout Int, base: String = "", chain: Set<String> = []) -> Stylesheet {
|
|
var parts = Parts()
|
|
let low = counter
|
|
var collector = XSLTUnitCollector(counter: counter, chain: chain)
|
|
collectUnit(top, loader: loader, base: base, into: &collector, imports: &parts)
|
|
counter = collector.counter
|
|
let precedence = counter
|
|
counter += 1
|
|
// Included declarations resolve their 7.1.1 namespace nodes via the
|
|
// weak parent chain to their own stylesheet element, retained only in
|
|
// the otherwise-unread retainedRoots; pin it so ARC keeps it here.
|
|
withExtendedLifetime(collector.retainedRoots) {
|
|
for (child, _) in collector.declarations {
|
|
_ = absorbDeclaration(child, into: &parts, precedence: precedence, low: low)
|
|
}
|
|
}
|
|
return parts.stylesheet
|
|
}
|
|
|
|
// Walks a unit's xsl children: imports compile immediately (in
|
|
// document order, so later ones take higher precedence), includes
|
|
// flatten recursively, other declarations are queued for the unit's
|
|
// own precedence.
|
|
|
|
private static func collectUnit(
|
|
_ top: XSLTTree,
|
|
loader: (String) -> String?,
|
|
base: String,
|
|
into collector: inout XSLTUnitCollector,
|
|
imports parts: inout Parts,
|
|
) {
|
|
for child in XSLTNode.elementChildren(top) where XSLTNode.isXSL(child) {
|
|
switch XSLTNode.localName(child) {
|
|
case "import":
|
|
let loadedImport = loadTree(child, loader: loader, base: base)
|
|
if let (tree, resolved) = loadedImport, !collector.chain.contains(resolved) {
|
|
collector.retainedRoots.append(tree)
|
|
parts.fold(compile(tree, loader: loader, counter: &collector.counter, base: resolved, chain: collector.chain.union([resolved])), isImport: true)
|
|
}
|
|
case "include":
|
|
let loadedInclude = loadTree(child, loader: loader, base: base)
|
|
if let (tree, resolved) = loadedInclude, !collector.chain.contains(resolved) {
|
|
collector.retainedRoots.append(tree)
|
|
// The include flattens into this unit: its href joins
|
|
// the chain for the nested walk and leaves with it.
|
|
collector.chain.insert(resolved)
|
|
collectUnit(tree, loader: loader, base: resolved, into: &collector, imports: &parts)
|
|
collector.chain.remove(resolved)
|
|
}
|
|
default:
|
|
collector.declarations.append((child, base))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Absorbs a non-composition top-level declaration, returning whether it
|
|
/// was one (so the caller can then try `include`/`import`).
|
|
private static func absorbDeclaration(_ child: XSLTTree, into parts: inout Parts, precedence: Int, low: Int) -> Bool {
|
|
switch XSLTNode.localName(child) {
|
|
case "template": parts.templates.append(template(child, precedence: precedence, low: low))
|
|
case "variable", "param": addGlobal(child, into: &parts)
|
|
case "key": parts.keys.append(key(child))
|
|
case "output": parts.output = parts.output.merged(with: parseOutput(child))
|
|
case "strip-space": parts.stripSpace.formUnion(elementNames(child))
|
|
case "preserve-space": parts.preserveSpace.formUnion(elementNames(child))
|
|
case "attribute-set": addAttributeSet(child, into: &parts)
|
|
case "decimal-format": parts.decimalFormats[XSLTNode.attribute(child, "name") ?? ""] = decimalFormat(child)
|
|
case "namespace-alias": addNamespaceAlias(child, into: &parts)
|
|
default: return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
/// A top-level xsl:variable or xsl:param; param names are recorded
|
|
/// so caller-supplied values can override their defaults.
|
|
private static func addGlobal(_ child: XSLTTree, into parts: inout Parts) {
|
|
parts.globals.append(variable(child))
|
|
if XSLTNode.localName(child) == "param", let name = XSLTNode.attribute(child, "name") {
|
|
parts.parameterNames.insert(name)
|
|
}
|
|
}
|
|
|
|
/// The whitespace-separated element name tests of an `xsl:strip-space` or
|
|
/// `xsl:preserve-space` element's `elements` attribute.
|
|
private static func elementNames(_ node: XSLTTree) -> Set<String> {
|
|
Set((XSLTNode.attribute(node, "elements") ?? "").split(whereSeparator: \.isWhitespace).map(String.init))
|
|
}
|
|
|
|
/// Loads an include/import target's stylesheet element: the href
|
|
/// resolves against the importing stylesheet's own URI, which becomes
|
|
/// the base for the loaded sheet's own includes and imports.
|
|
private static func loadTree(_ node: XSLTTree, loader: (String) -> String?, base: String) -> (XSLTTree, String)? {
|
|
guard let href = XSLTNode.attribute(node, "href") else { return nil }
|
|
let resolved = base.isEmpty ? href : PureXML.XInclude.URIReference.resolve(href, against: base)
|
|
guard let text = loader(resolved),
|
|
let root = try? PureXML.parseTree(text, limits: .init(allowDoctype: true)), let top = stylesheetElement(root)
|
|
else {
|
|
return nil
|
|
}
|
|
return (top, resolved)
|
|
}
|
|
|
|
private static func parseOutput(_ node: XSLTTree) -> Output {
|
|
Output(
|
|
method: XSLTNode.attribute(node, "method"),
|
|
indent: XSLTNode.attribute(node, "indent").map { $0 == "yes" },
|
|
omitXMLDeclaration: XSLTNode.attribute(node, "omit-xml-declaration").map { $0 == "yes" },
|
|
encoding: XSLTNode.attribute(node, "encoding"),
|
|
version: XSLTNode.attribute(node, "version"),
|
|
standalone: XSLTNode.attribute(node, "standalone").map { $0 == "yes" },
|
|
doctypePublic: XSLTNode.attribute(node, "doctype-public"),
|
|
doctypeSystem: XSLTNode.attribute(node, "doctype-system"),
|
|
cdataSectionElements: Set((XSLTNode.attribute(node, "cdata-section-elements") ?? "").split(whereSeparator: \.isWhitespace).map(String.init)),
|
|
)
|
|
}
|
|
|
|
private static func key(_ node: XSLTTree) -> Key {
|
|
Key(
|
|
name: XSLTNode.attribute(node, "name") ?? "",
|
|
match: XSLTNode.attribute(node, "match") ?? "",
|
|
use: XSLTNode.attribute(node, "use") ?? ".",
|
|
)
|
|
}
|
|
|
|
// MARK: Templates
|
|
|
|
private static func template(_ node: XSLTTree, precedence: Int, low: Int) -> Template {
|
|
let match = XSLTNode.attribute(node, "match")
|
|
let priority = XSLTNode.attribute(node, "priority").flatMap(Double.init)
|
|
?? match.map(defaultPriority) ?? 0
|
|
let parameters = XSLTNode.children(node, named: "param").map(binding)
|
|
let body = node.children
|
|
.filter { !(XSLTNode.isXSL($0) && XSLTNode.localName($0) == "param") }
|
|
.compactMap(instruction)
|
|
return Template(
|
|
match: match,
|
|
name: XSLTNode.attribute(node, "name"),
|
|
mode: expandedMode(node),
|
|
priority: priority,
|
|
importPrecedence: precedence,
|
|
importRangeLow: low,
|
|
parameters: parameters,
|
|
body: body,
|
|
namespaces: inScopeNamespaces(node).filter { !$0.key.isEmpty },
|
|
)
|
|
}
|
|
|
|
private static func binding(_ node: XSLTTree) -> Binding {
|
|
Binding(
|
|
name: expandedDeclaredName(node),
|
|
select: XSLTNode.attribute(node, "select"),
|
|
body: body(node),
|
|
)
|
|
}
|
|
|
|
private static func withParameters(_ node: XSLTTree) -> [Binding] {
|
|
XSLTNode.children(node, named: "with-param").map(binding)
|
|
}
|
|
|
|
/// The XSLT default-priority rules for a match pattern.
|
|
static func defaultPriority(_ pattern: String) -> Double {
|
|
if pattern.contains("/") || pattern.contains("[") { return 0.5 }
|
|
if ["*", "@*", "node()", "text()", "comment()"].contains(pattern) { return -0.5 }
|
|
if pattern.hasSuffix(":*") { return -0.25 }
|
|
return 0
|
|
}
|
|
|
|
// MARK: Bodies and instructions
|
|
|
|
static func body(_ node: XSLTTree) -> [Instruction] {
|
|
// Adjacent text and CDATA children are one text node in the data
|
|
// model, so a whitespace-only run is dropped (XSLT 1.0 3.4) only when
|
|
// the WHOLE coalesced run is whitespace: " <![CDATA[x]]> " keeps its
|
|
// spaces because the run "x" surrounds them with non-whitespace.
|
|
var result: [Instruction] = []
|
|
var run = ""
|
|
func flush() {
|
|
if !run.isEmpty, !run.unicodeScalars.allSatisfy(PureXML.Parsing.XMLCharacter.isWhitespace) { result.append(.literalText(run)) }
|
|
run = ""
|
|
}
|
|
for child in node.children {
|
|
if child.kind == .text || child.kind == .cdata {
|
|
run += child.value
|
|
} else {
|
|
flush()
|
|
if let instruction = instruction(child) { result.append(instruction) }
|
|
}
|
|
}
|
|
flush()
|
|
return result
|
|
}
|
|
|
|
static func instruction(_ node: XSLTTree) -> Instruction? {
|
|
switch node.kind {
|
|
case .text, .cdata:
|
|
let value = node.value
|
|
return value.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" } ? nil : .literalText(value)
|
|
case .element:
|
|
return XSLTNode.isXSL(node) ? xslInstruction(node) : literalElement(node)
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
private static func xslInstruction(_ node: XSLTTree) -> Instruction? {
|
|
if let known = simpleInstruction(node) ?? structuralInstruction(node) { return known }
|
|
// An unrecognized XSLT element instantiates its xsl:fallback children
|
|
// (forwards-compatible processing); with none, it is dropped.
|
|
let fallback = XSLTNode.children(node, named: "fallback").flatMap(body)
|
|
return fallback.isEmpty ? nil : .fallback(body: fallback)
|
|
}
|
|
|
|
private static func simpleInstruction(_ node: XSLTTree) -> Instruction? {
|
|
switch XSLTNode.localName(node) {
|
|
case "value-of": .valueOf(
|
|
select: XSLTNode.attribute(node, "select") ?? "",
|
|
raw: XSLTNode.attribute(node, "disable-output-escaping") == "yes",
|
|
)
|
|
case "apply-templates": .applyTemplates(
|
|
select: XSLTNode.attribute(node, "select"),
|
|
mode: expandedMode(node),
|
|
sorts: sorts(node),
|
|
parameters: withParameters(node),
|
|
)
|
|
case "copy-of": .copyOf(select: XSLTNode.attribute(node, "select") ?? "")
|
|
case "call-template": .callTemplate(
|
|
name: XSLTNode.attribute(node, "name") ?? "",
|
|
parameters: withParameters(node),
|
|
)
|
|
case "text": .literalText(
|
|
XSLTNode.attribute(node, "disable-output-escaping") == "yes"
|
|
? PureXML.XSLT.RawText.marked(node.stringValue)
|
|
: node.stringValue,
|
|
)
|
|
case "variable", "param": variable(node)
|
|
case "copy": .copy(useAttributeSets: useAttributeSets(node), body: body(node))
|
|
case "message": .message(terminate: XSLTNode.attribute(node, "terminate") == "yes", body: body(node))
|
|
case "apply-imports": .applyImports
|
|
default: nil
|
|
}
|
|
}
|
|
|
|
private static func variable(_ node: XSLTTree) -> Instruction {
|
|
.variable(name: expandedDeclaredName(node), select: XSLTNode.attribute(node, "select"), body: body(node))
|
|
}
|
|
|
|
static func choose(_ node: XSLTTree) -> Instruction {
|
|
let whens = XSLTNode.children(node, named: "when").map { branch in
|
|
Branch(test: XSLTNode.attribute(branch, "test") ?? "", body: body(branch))
|
|
}
|
|
let otherwise = XSLTNode.children(node, named: "otherwise").first.map(body) ?? []
|
|
return .choose(whens: whens, otherwise: otherwise)
|
|
}
|
|
|
|
private static func literalElement(_ node: XSLTTree) -> Instruction {
|
|
guard let name = node.name else { return .literalText("") }
|
|
// xmlns declarations and the special xsl:* attributes (use-attribute-sets,
|
|
// version, exclude-result-prefixes …) are not copied to the output.
|
|
let attributes = node.attributes
|
|
.filter { $0.name.prefix != "xmlns" && !($0.name.prefix == nil && $0.name.localName == "xmlns") && $0.name.prefix != "xsl" }
|
|
.map { LiteralAttribute(name: $0.name, value: valueTemplate($0.value)) }
|
|
return .literalElement(
|
|
name: name,
|
|
attributes: attributes,
|
|
namespaces: copiedNamespaces(node),
|
|
useAttributeSets: useAttributeSets(node),
|
|
body: body(node),
|
|
)
|
|
}
|
|
|
|
/// The whitespace-separated names of `[xsl:]use-attribute-sets` on `node`.
|
|
static func useAttributeSets(_ node: XSLTTree) -> [String] {
|
|
(XSLTNode.attribute(node, "use-attribute-sets") ?? "").split(whereSeparator: \.isWhitespace).map(String.init)
|
|
}
|
|
|
|
private static func caseOrder(_ node: XSLTTree) -> PureXML.XSLT.CaseOrder? {
|
|
switch XSLTNode.attribute(node, "case-order") {
|
|
case "upper-first": .upperFirst
|
|
case "lower-first": .lowerFirst
|
|
default: nil
|
|
}
|
|
}
|
|
|
|
static func sorts(_ node: XSLTTree) -> [Sort] {
|
|
XSLTNode.children(node, named: "sort").map { sort in
|
|
Sort(
|
|
select: XSLTNode.attribute(sort, "select") ?? ".",
|
|
descending: XSLTNode.attribute(sort, "order") == "descending",
|
|
numeric: XSLTNode.attribute(sort, "data-type") == "number",
|
|
caseOrder: caseOrder(sort),
|
|
lang: XSLTNode.attribute(sort, "lang").map(valueTemplate),
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|