PureXML/Sources/XSLT/XSLTMatchCache.swift
Mihaela Mihaljevic b41678064e feat(xslt): templates over attribute and namespace nodes
apply-templates and for-each keep attribute and namespace nodes in
their selections; the context carries the non-tree current node with
its owner element backing the tree-only machinery, XPath evaluation
and current() start from it, match patterns select attribute nodes
through attribute identities in the match cache, the built-in rules
copy an attribute's or namespace's value as text, xsl:copy copies the
focused attribute or declaration itself, and an attribute result
arriving after element content is ignored (the XSLT recovery).
Sorting, for-each, and choose move to XSLTSorting.swift for the file
caps. Xalan baseline 352 -> 292 (axes 35 -> 16, copy 29 -> 16).
2026-06-10 13:24:31 +02:00

59 lines
2.6 KiB
Swift

/// What one match pattern selected: tree-node and attribute identities.
private struct PatternMatches {
var trees: Set<ObjectIdentifier> = []
var attributes: Set<PureXML.XSLT.AttributeIdentity> = []
}
extension PureXML.XSLT {
/// An attribute node's identity: its owner's identity plus its name.
struct AttributeIdentity: Hashable {
let owner: ObjectIdentifier
let name: String
}
/// Caches, per transform, the node set each match pattern selects over the
/// source tree (tree nodes and attribute nodes), so a pattern is compiled
/// and evaluated once per document rather than once per (node, template)
/// pair during template selection.
final class MatchCache {
private var matched: [String: PatternMatches] = [:]
/// The identities of the tree nodes `pattern` selects over `root`.
func nodes(matching pattern: String, over root: PureXML.Model.TreeNode) -> Set<ObjectIdentifier> {
compute(pattern, root).trees
}
/// The identities of the attribute nodes `pattern` selects over `root`.
func attributes(matching pattern: String, over root: PureXML.Model.TreeNode) -> Set<AttributeIdentity> {
compute(pattern, root).attributes
}
/// Computed and cached on first use; a branch that fails to compile
/// selects nothing.
private func compute(_ pattern: String, _ root: PureXML.Model.TreeNode) -> PatternMatches {
if let cached = matched[pattern] { return cached }
var result = PatternMatches()
for branch in pattern.split(separator: "|") {
let trimmed = branch.trimmingXMLWhitespace()
let path = trimmed.hasPrefix("/") ? trimmed : "//" + trimmed
guard let query = try? PureXML.XPath.Query(path),
let value = try? query.value(atNode: .tree(root), position: 1, size: 1, variables: [:], functions: PureXML.XPath.FunctionTable()),
let selected = value.nodes
else { continue }
for node in selected {
switch node {
case let .tree(tree):
result.trees.insert(ObjectIdentifier(tree))
case let .attribute(owner, attribute):
result.attributes.insert(AttributeIdentity(owner: ObjectIdentifier(owner), name: attribute.name.description))
case .namespace:
break
}
}
}
matched[pattern] = result
return result
}
}
}