Optimize XPath step#315
Open
tompng wants to merge 1 commit into
Open
Conversation
There was a problem hiding this comment.
Pull request overview
This PR refactors XPath step evaluation in REXML::XPathParser to defer nodeset materialization and introduce axis “scan strategies” that can fast-path common predicate shapes (position-independent and simple positional predicates), improving performance for deep and wide-tree queries.
Changes:
- Reworked
stepto drive axis scans via[scanner_method, scanner_argument]and choose scanning strategies (:uniq,[op, value],:nodesets) based on predicate classification. - Added optimized scanners for
descendant(-or-self),ancestor(-or-self), and sibling axes, plus a shared fallback selection path. - Added/updated XPath predicate and sibling-axis tests, including float literal predicates and positional comparisons.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| lib/rexml/xpath_parser.rb | Implements deferred scanning/strategy selection in step, predicate classification, and optimized axis scanners. |
| test/xpath/test_predicate.rb | Adds coverage for float-literal positional predicates and variable-as-position predicates. |
| test/xpath/test_base.rb | Adds test for following-sibling::* with position() < N and adjusts nested-predicate test behavior. |
| test/xpath/test_axis_preceding_sibling.rb | Adds tests for preceding-sibling:: with < and <= position predicates. |
Comments suppressed due to low confidence (1)
lib/rexml/xpath_parser.rb:834
descendantaxis fast path callsraw_node.childrenwheninclude_selfis false without checking the node type or whetherchildrenexists. If the context node is not an element/document (e.g., an attribute node), this will raiseNoMethodError; previously it would just yield an empty descendant set. Guard this branch so it only iterateschildrenfor element/document nodes (or use the same node_type check as inrecursive).
raw_nodes.each do |raw_node|
if include_self
recursive.call(raw_node)
else
raw_node.children.each(&recursive)
end
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+441
to
+446
| def preceding_following_sibling(raw_nodes, tester, selector, reverse:) | ||
| raw_nodes = raw_nodes.select(&:parent) | ||
| case selector | ||
| when :uniq | ||
| raw_nodes.group_by(&:parent).flat_map do |parent, sibling_nodes| | ||
| sets = {}.compare_by_identity |
6f94f2e to
c4a1440
Compare
c4a1440 to
67e3270
Compare
67e3270 to
593620b
Compare
Comment on lines
+361
to
+362
| result = evaluate_predicate(predicate_expr.dclone, [result]).first || [] | ||
| end |
| end | ||
|
|
||
| def preceding_following_sibling(raw_nodes, tester, selector, reverse:) | ||
| raw_nodes = raw_nodes.select(&:parent) |
593620b to
65c5103
Compare
65c5103 to
15a8f52
Compare
Comment on lines
+658
to
+660
| # For xpath like `(/path[predicate1][predicate2])[predicate3][predicate4]`, | ||
| # add a separator mark to distinguish predicates of the inner parentheses and the outer parentheses. | ||
| parsed.push(:self, :node) if n[0] == :document || n[0] == :child |
| # If there are no position-based predicates, | ||
| # return [position_independent_predicates, nil, [], nil] | ||
| # If there are only one simple position-based predicate, | ||
| # return [position_independent_predicates, position_operator, position_independent_predicates, nil] |
If a predicate of xpath is position-independent, we don't need to create nodesets that has many duplicated nodes with different positions.
15a8f52 to
020085a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refactor
stepso that nodeset materialization is deferred. Instead of building the full nodeset up front and filtering through predicates,each axis returns a scan descriptor (
[generator_name, generator_argument]), andsteppicks a scan strategy based on the predicates' shape.Predicates are classified into three groups:
[@a="1"],[name()="foo"],[@a=@b]:uniq— emit deduplicated matching nodes[N],[position()=N],[position()>N],[position()<N][op, value]— positional scan with one comparison[position()*@a],[last()-1], ...:nodesets— fall back to per-anchor nodesets + the previousevaluate_predicatepipelineMixed predicate lists are split: position-independent predicates before the first positional predicate are folded into the node test;
predicates after it are applied per-node on the result.
Each axis can implement zero, one, or all of the three strategies. If a strategy is not implemented, the generator falls back to producing
:nodesetsand the common slow path (non_optimized_raw_nodesets_select) handles dedup / positional filtering on flattened nodesets — i.e. thesame behavior as before this PR.
This pull request adds fast paths for:
descendant/descendant-or-self::uniq(single DFS with a seen-set; this is what speeds up//a//a//a//a)ancestor/ancestor-or-self::uniq(parent-chain walk with a seen-set)preceding-sibling/following-sibling::uniqand[op, value](sibling scan with anchor-index tracking)Other axes (
child,parent,self,attribute) keep the previous behavior via the fallback path; they can be optimized infollow-ups without changing call sites.
Detail
For
//a//a//astyle queries, the previous code built nodesets keyed by each anchor, including the same descendant once per anchor. The new:uniqpath scans every node at most once per step.For
[position() > N]style predicates on wide trees (e.g.//a/preceding-sibling::*[position()>2]), we previously built the fullpreceding-sibling nodeset for each anchor and then ran
evaluate_predicate. The new[op, value]path scans children once per parent and usesanchor-index bookkeeping to recover per-anchor positions.
Note: general XPath cannot be linear — e.g.
*[position() * number(@a) % number(@b) = 1]is genuinely O(n²) — so the goal is only to fast-pathposition-independent and simple-positional predicates.
Benchmark
Also fixes #25