diff --git a/CHANGELOG.md b/CHANGELOG.md index 8412843..3359c66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- The `following-sibling` and `preceding-sibling` axes no longer scan the parent's child list to locate the context node on every call, and fuse the step's node test into the walk. Locating the context among a wide parent's children was a linear scan independent of the result, so the axes were quadratic over many context siblings; the index now comes from the shared per-evaluation sibling-index cache, and a sibling the node test rejects is never wrapped. The selected siblings and their order are unchanged. Over a wide parent the gratuitous per-context scan and the non-match wrapping are removed (the per-context iteration over the siblings themselves is inherent to the axis). Guarded by `SiblingAxisTests`. + - Sorting many attribute nodes from the same element into document order is no longer quadratic in the attribute count. An attribute's document-order key bands by its index among its owner's attributes, which was found by a linear scan of the attribute list on every attribute, so sorting an element's K attributes was O(K^2). The index now comes from a cached per-owner name-to-index map (built once on the second lookup, mirroring the sibling-index cache). The order is unchanged. Sorting the attributes of an 8000-attribute element drops from about 0.18 s to about 0.01 s (~16x), and the cost is now linear. Guarded by `AttributeDocumentOrderTests`. - The `following` and `preceding` axes no longer rebuild the whole document node list and linearly search it on every context node, which made them quadratic over many context nodes. They now share a per-evaluation cache of each document's ordered node list and a node-to-index map (the document does not change during evaluation), so the list is built once and a node's position is an O(1) lookup; `following` additionally skips the context's contiguous subtree by index arithmetic rather than filtering every descendant out. The step's node test is fused into the walk, so a node the test rejects is never copied out of the shared list (only the matches are materialized). The selected nodes and their order are unchanged. A 200-context `following::` query over a 20k-element document drops from about 16 s to about 6 s. Guarded by `FollowingPrecedingAxisTests`. diff --git a/Sources/XPath/AxisNavigation.swift b/Sources/XPath/AxisNavigation.swift index 4271101..5da3cd1 100644 --- a/Sources/XPath/AxisNavigation.swift +++ b/Sources/XPath/AxisNavigation.swift @@ -5,8 +5,14 @@ extension PureXML.XPath { enum AxisNavigation { private static let xmlNamespaceURI = "http://www.w3.org/XML/1998/namespace" - static func nodes(on axis: Axis, from context: Node, cache: DocumentNavigationCache? = nil) -> [Node] { - verticalNodes(on: axis, from: context) ?? lateralNodes(on: axis, from: context, cache: cache) + static func nodes( + on axis: Axis, + from context: Node, + cache: DocumentNavigationCache? = nil, + siblingCache: SiblingIndexCache? = nil, + ) -> [Node] { + verticalNodes(on: axis, from: context) + ?? lateralNodes(on: axis, from: context, cache: cache, siblingCache: siblingCache) } /// The self, child, descendant, parent, and ancestor families; nil for an @@ -25,10 +31,15 @@ extension PureXML.XPath { } /// The sibling, following/preceding, attribute, and namespace axes. - private static func lateralNodes(on axis: Axis, from context: Node, cache: DocumentNavigationCache?) -> [Node] { + private static func lateralNodes( + on axis: Axis, + from context: Node, + cache: DocumentNavigationCache?, + siblingCache: SiblingIndexCache?, + ) -> [Node] { switch axis { - case .followingSibling: followingSiblings(of: context) - case .precedingSibling: precedingSiblings(of: context) + case .followingSibling: followingSiblings(of: context, siblingCache: siblingCache, where: { _ in true }) + case .precedingSibling: precedingSiblings(of: context, siblingCache: siblingCache, where: { _ in true }) case .following: following(of: context, cache: cache, where: { _ in true }) case .preceding: preceding(of: context, cache: cache, where: { _ in true }) case .attribute: attributes(of: context) @@ -109,14 +120,20 @@ extension PureXML.XPath { return result } - private static func followingSiblings(of node: Node) -> [Node] { - guard let (parent, index) = siblingPosition(of: node) else { return [] } - return parent.children[(index + 1)...].map(Node.tree) + /// The following-sibling axis, fusing the step's node test into the walk: + /// the raw child ``TreeNode`` is tested before it is wrapped, so a sibling + /// the test rejects is never wrapped (and never retained). The unfused + /// caller passes a test that keeps everything. + static func followingSiblings(of node: Node, siblingCache: SiblingIndexCache?, where keep: (PureXML.Model.TreeNode) -> Bool) -> [Node] { + guard let (parent, index) = siblingPosition(of: node, cache: siblingCache) else { return [] } + return parent.children[(index + 1)...].compactMap { keep($0) ? Node.tree($0) : nil } } - private static func precedingSiblings(of node: Node) -> [Node] { - guard let (parent, index) = siblingPosition(of: node) else { return [] } - return parent.children[.. Bool) -> [Node] { + guard let (parent, index) = siblingPosition(of: node, cache: siblingCache) else { return [] } + return parent.children[.. (PureXML.Model.TreeNode, Int)? { + private static func siblingPosition(of node: Node, cache: SiblingIndexCache?) -> (PureXML.Model.TreeNode, Int)? { guard case let .tree(tree) = node, let parent = tree.parent else { return nil } + // A node is always among its parent's children, so the cache's index + // is exact; without one, scanning the sibling list per node makes the + // sibling axes quadratic over a wide parent. + if let cache { + return (parent, cache.index(of: tree, in: parent)) + } guard let index = parent.children.firstIndex(where: { $0 === tree }) else { return nil } return (parent, index) } diff --git a/Sources/XPath/EvaluationContext.swift b/Sources/XPath/EvaluationContext.swift index 1a6a271..56d6aa5 100644 --- a/Sources/XPath/EvaluationContext.swift +++ b/Sources/XPath/EvaluationContext.swift @@ -22,6 +22,10 @@ extension PureXML.XPath { /// cache each document's ordered node list here instead of rebuilding it /// per context node. let documentNavigation = DocumentNavigationCache() + /// Shared across the whole evaluation: the following-sibling and + /// preceding-sibling axes look up a node's index among its parent's + /// children here instead of scanning the sibling list per node. + let siblingIndex = SiblingIndexCache() init(variables: [String: Value], functions: FunctionTable, namespaces: [String: String], budget: Budget?) { self.variables = variables diff --git a/Sources/XPath/EvaluatorSteps.swift b/Sources/XPath/EvaluatorSteps.swift index b36d3d0..d583919 100644 --- a/Sources/XPath/EvaluatorSteps.swift +++ b/Sources/XPath/EvaluatorSteps.swift @@ -67,17 +67,26 @@ extension PureXML.XPath.Evaluator { default: break } } - let keep = compiledNodeTest(step.test, on: step.axis, context.namespaces) let cache = context.environment.documentNavigation - // The following and preceding axes fuse the node test into the walk so a - // rejected node is never copied out of the cached document node list; the - // other axes build their list and filter it. + let siblingCache = context.environment.siblingIndex + // The following/preceding and following-sibling/preceding-sibling axes + // fuse the node test into the walk so a rejected node is never wrapped or + // copied out; the other axes build their node list and filter it. switch step.axis { case .following: + let keep = compiledNodeTest(step.test, on: step.axis, context.namespaces) return PureXML.XPath.AxisNavigation.following(of: contextNode, cache: cache, where: keep) case .preceding: + let keep = compiledNodeTest(step.test, on: step.axis, context.namespaces) return PureXML.XPath.AxisNavigation.preceding(of: contextNode, cache: cache, where: keep) + case .followingSibling: + let keep = compiledTreeTest(step.test, on: step.axis, context.namespaces) + return PureXML.XPath.AxisNavigation.followingSiblings(of: contextNode, siblingCache: siblingCache, where: keep) + case .precedingSibling: + let keep = compiledTreeTest(step.test, on: step.axis, context.namespaces) + return PureXML.XPath.AxisNavigation.precedingSiblings(of: contextNode, siblingCache: siblingCache, where: keep) default: + let keep = compiledNodeTest(step.test, on: step.axis, context.namespaces) return PureXML.XPath.AxisNavigation.nodes(on: step.axis, from: contextNode, cache: cache).filter(keep) } } diff --git a/Tests/SiblingAxisTests.swift b/Tests/SiblingAxisTests.swift new file mode 100644 index 0000000..ebb71fd --- /dev/null +++ b/Tests/SiblingAxisTests.swift @@ -0,0 +1,44 @@ +import Testing +@testable import PureXML + +/// The following-sibling and preceding-sibling axes look up a node's index among +/// its parent's children through a shared cache (not a scan per context node) +/// and fuse the step's node test into the walk (a rejected sibling is never +/// wrapped). These pin that the selected siblings and their order are unchanged: +/// a name test selects only matching siblings, and the path result is in +/// document order for both axes. +@Suite("following-sibling and preceding-sibling axes") +struct SiblingAxisTests { + private static let doc = "" + + private func names(_ path: String) throws -> [String] { + try PureXML.XPath.Query(path).evaluate(over: PureXML.parse(Self.doc)).compactMap { + if case let .node(node) = $0 { return node.element?.name.localName } + return nil + } + } + + @Test("following-sibling selects later siblings in document order") + func test_following() throws { + #expect(try names("//b/following-sibling::*") == ["c", "a", "d"]) + // A name test keeps only the matching siblings (the fused node test). + #expect(try names("//b/following-sibling::a") == ["a"]) + #expect(try names("//d/following-sibling::*") == []) + } + + @Test("preceding-sibling selects earlier siblings (path result in document order)") + func test_preceding() throws { + #expect(try names("//c/preceding-sibling::*") == ["a", "b"]) + #expect(try names("//d/preceding-sibling::a") == ["a", "a"]) + #expect(try names("//a/preceding-sibling::*") == ["a", "b", "c"]) + } + + @Test("the axes are correct across many context nodes (shared cache)") + func test_manyContexts() throws { + let xml = "" + String(repeating: "", count: 60) + "" + // Each x[i] has 60 - i following x siblings; the deduplicated union is the + // 59 x's after the first. + let total = try Int(PureXML.XPath.Query("count(//x/following-sibling::x)").value(at: PureXML.parseTree(xml)).number) + #expect(total == 59) + } +}